0

在以下代码中,为什么无法执行此取消引用:*arr = 'e'. 输出不应该是字符'e'吗?

int main ()
{
    char *arr = "abt";
    arr++;
    * arr='e'; // This is where I guess the problem is occurring.
    cout << arr[0];

    system("pause");

}

我收到以下错误:

Arrays.exe 中 0x00a91da1 处的未处理异常:0xC0000005:访问冲突写入位置 0x00a97839。

4

2 回答 2

3

"abt"是所谓的字符串文字常量,任何修改它的尝试都会导致未定义的行为*arr='e';

于 2012-07-01T23:12:00.860 回答
0
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 程序的典型内存表示由以下部分组成。

  1. 文本段
  2. 初始化数据段
  3. 未初始化的数据段

而像 const char* string = "hello world" 这样的 C 语句使字符串字面量“hello world”存储在初始化的只读区域中,并将字符指针变量字符串存储在初始化的读写区域中。

于 2012-07-01T23:23:33.580 回答