为什么增加指针崩溃指向的数据?
问题描述:
Possible Duplicate:
C/C++ Char Pointer Crash为什么增加指针崩溃指向的数据?
char *p = "atl";
char c;
c = ++*p; //crashing here
为什么崩溃?
我知道内存不是为指针增量创建的,应该在数据上完成。
答
p
指向const
数据是字符串文字"atl"
;这意味着,*p
无法更改。但是您正在尝试通过编写++*p
来更改它。这就是它在运行时崩溃的原因。
事实上,大多数编译器会在编写char *p ="atl"
时发出警告。你应该写:
const char *p ="atl";
如果你写的话,那么当你在编译的时候自己写++*p
编译器会给出错误。在编译时检测错误比在运行时检测错误要好。看到这里的编译错误现在:
的编译错误是:
prog.cpp:7: error: increment of read-only location ‘* p’
但是,如果你写
char p[] = "atl";
char c = ++*p; //ok
那么现在它的正确。因为现在p
是一个数组,它是由字符串文字"atl"
创建的。它不再指向字符串文字本身了。所以你可以改变数组的内容。
这个问题已被问了很多很多次之前:http://stackoverflow.com/questions/4226829/cc-char-pointer-crash http://stackoverflow.com/questions/2437318/why-does-this -code-crash http://stackoverflow.com/questions/5972915/string-constants-vs-char-arrays-in-c http://stackoverflow.com/questions/5142988/c-pointer-arithmetic-on-characters http://stackoverflow.com/questions/3090610/c-char-pointer-problem仅举几例 –