int main ()
{
char *arr= "abt"; // This could be OK on some compilers ... and give an access violation on others
arr++;
*arr='e'; // This is where I guess the problem is occurring.
cout<<arr[0];
system("pause");
}
相比之下:
int main ()
{
char arr[80]= "abt"; // This will work
char *p = arr;
p++; // Increments to 2nd element of "arr"
*(++p)='c'; // now spells "abc"
cout << "arr=" << arr << ",p=" << p << "\n"; // OUTPUT: arr=abc,p=c
return 0;
}
此链接和图表解释了“为什么”:
http://www.geeksforgeeks.org/archives/14268
C 程序的内存布局
C 程序的典型内存表示由以下部分组成。
- 文本段
- 初始化数据段
- 未初始化的数据段
- 堆
- 堆
而像 const char* string = "hello world" 这样的 C 语句使字符串字面量“hello world”存储在初始化的只读区域中,并将字符指针变量字符串存储在初始化的读写区域中。