2012-07-01 60 views
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"); 

} 

我收到以下錯誤:

Unhandled exception at 0x00a91da1 in Arrays.exe: 0xC0000005: Access violation writing location 0x00a97839.

+0

如果 「ABT」 是常量字符串文字,那麼爲什麼下面的代碼修改相同的常量字面量:int main(void) { \t char arr [] =「abt」; \t arr [0] ='e'; \t cout << arr [0]; \t system(「pause」); } –

+0

可能的重複[爲什麼這C代碼導致分段錯誤?](http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault) – AnT

回答

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

Memory Layout of C Programs

A typical memory representation of C program consists of following sections.

  1. Text segment
  2. Initialized data segment
  3. Uninitialized data segment
  4. Stack
  5. Heap

And a C statement like const char* string = "hello world" makes the string literal "hello world" to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.

+0

感謝您的幫助! –

+2

除了你的版本'arr'不是一個左值,所以你不能增加它...... – Neil

+0

第二個「固定」的例子是錯誤的,你不能在數組上做'arr ++;'。 –

3

"abt"是所謂的字符串字面常量,任何企圖修改導致未定義的行爲*arr='e';

+1

然後爲什麼我能夠做到以下幾點:int main(void) { \t char arr [] =「abt」; \t arr [0] ='e'; \t cout << arr [0]; \t system(「pause」); } –

+0

@JohnNash,[它已經被問及很久纔回復您發佈...](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-和char-s-in-c) – Griwes

+1

'char arr [] =「abt」;'是一個字符數組,'char * arr =「abt」;'是一個指向字符串的指針,只有記憶。 –