我在Win8中 使用codeblock编写了一段程序。使用的是GCC 4.7 & 4.8 编译器:
#include <iostream>
using namespace std;
int main()
{
int *i=0;
cout<< "Hello world!" << endl;
return 0;
}
程序可以运行,输出:Hello world。很奇怪的是一旦加入指针赋值语句,编译组建通过,但无法运行。
int main()
{
int *i=0;
*i = 9;
cout<< "Hello world!" << endl;
return 0;
}
控制台上显示为:
Process returned -1073741819 (0xC0000005) execution time : 1.453 s
使用VC++ 6.0 出现了同样的现象
在百度上也没搜到结果。
This statement is equivalent to assigning the pointer variable i of
int*
to 0, instead of pointing the pointer i ofint*
to the memory address where the constant 0 is located, which is equivalent to the following code:instead of
Is this what you understand? @changqngd
I just ran it a few times and thought about it, and finally figured it out.
The error is:
int *i=0; //这里给指针赋了一个空地址 *i = 9;
//*i is a null address pointer and cannot be usedIt is correct to change it to the following: