2015-10-04 82 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字符串是指针字符串不能被修饰。原因是指针字符串存储在代码存储器中,数组字符串存储在堆栈中(如果它是堆全局数组)

相关问题