2015-10-04 78 views
-1

char * const pstr = "abcd"; PSTR是一個const字符指針...... 我想,我不能修改PSTR,但我可以修改* PSTR, 所以我寫了下面的代碼段錯誤時修改char * const pstr =「abcd」;

#include <stdio.h> 
#include <stdlib.h> 
int main(void) 
{ 
    // The pointer itself is a constant, 
    // Point to cannot be modified, 
    // But point to a string can be modified 
    char * const pstr = "abcd"; // Pointer to a constant 

    // I find that pstr(the address of "abcd") is in ReadOnly data 
    // &pstr(the address of pstr) is in stack segment 
    printf("%p %p\n", pstr, &pstr); 

    *(pstr + 2) = 'e'; // segmentation fault (core dumped) 
    printf("%c\n", *(pstr + 2)); 

    return EXIT_SUCCESS; 
} 

但結果不像我預料的那樣。 我得到了segmentation fault (core dumped)在線路14 ... 所以我寫了下面的代碼

#include <stdio.h> 
#include <stdlib.h> 


int main(void) 
{ 
    // The pointer itself is a constant, 
    // Point to cannot be modified, 
    // But point to a string can be modified 
    char * const pstr = "abcd"; // Pointer to a constant 

    // I find that pstr(the address of "abcd") is in ReadOnly data 
    // &pstr(the address of pstr) is in Stack segment 
    printf("%p %p\n", pstr, &pstr); 

    *(pstr + 2) = 'e'; // segmentation fault (core dumped) 
    printf("%c\n", *(pstr + 2)); 

    return EXIT_SUCCESS; 

}

但我不知道是什麼原因???

+1

您正在嘗試修改字符串文字。請參見[this](http://stackoverflow.com/questions/10202013/change-string-literal-in-c-through-pointer)。 – SSWilks

+4

可能的重複[爲什麼在寫入使用「char \ * s」初始化但不是「char s \ [\]」的字符串時出現分段錯誤?](http://stackoverflow.com/questions/164194/爲什麼-DO-I-GET-A-分割的故障時,寫入到一個字符串初始化-與-CHA) – SSWilks

回答

0

在C語言中,如果我會寫

char *ptr = "abcd" 

你不能改變*(PTR + 2)= 'E',即使你不寫常量。就像在C語言中一樣,如果你聲明像char * ptr =「abcd」,它將把ptr當作常量字符串。

所以它會給分段故障在這段代碼也..

char *ptr = "abcd"; 
*(ptr+2) = 'e'; 

但是,你可以這樣做::

char ptr[] = "abcd"; 
*(ptr+2) = 'e'; 
2
char * const pstr = "abcd"; 

pstr是一個常量指針char和你無法修改pstr正確,但"abcd"是一個字符串迭代。你不能修改字符串文字。

您嘗試對其進行修改,因此會出現分段錯誤。

0

char * const pstr = "abcd"

這是指針初始化。所以「abcd」存儲在內存的代碼部分。你不能修改內存的代碼段。它是隻讀存儲器。所以。由於訪問未經授權的內存,操作系統在運行時會產生分段錯誤。

char pstr[]="abcd"; 

現在,「abcd」存儲在數據部分,所以你可以修改。

0

由數組和字符串初始化的字符串初始化的區別b/w字符串是指針字符串不能被修飾。原因是指針字符串存儲在代碼存儲器中,數組字符串存儲在堆棧中(如果它是堆全局數組)

相關問題