无法取消引用

Unable to dereference

本文关键字:引用 取消      更新时间:2023-10-16

在下面的代码中,为什么无法进行这种取消引用:*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");
}

我收到以下错误:

数组

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

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

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* 字符串 = "hello world" 这样的 C 语句使 字符串文字"hello world"存储在初始化的只读中 区域中和字符指针变量字符串初始化 读写区域。