修改char * const pstr =" abcd&#34 ;;

时间:2015-10-04 12:57:31

标签: c point

char * const pstr = "abcd"; pstr是一个指向char的const指针... 我认为我无法修改pstr,但我可以修改* pstr, 所以我写下一个代码

#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;
}

但结果并不像我预期的那样。 我在第14行得到segmentation fault (core dumped) ... 所以我写下一个代码

#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;

}

但我不知道为什么???

4 个答案:

答案 0 :(得分:2)

char * const pstr = "abcd"; 

pstr是指向char的常量指针,您无法修改pstr正确,但"abcd"是字符串迭代。而你无法修改字符串文字。

您尝试修改它,因此会出现分段错误。

答案 1 :(得分:0)

在C语言中,如果我要写

char *ptr = "abcd"

你不能改变*(ptr + 2)='e',即使你不写const。如在C语言中,如果声明为char * ptr =“abcd”,它会将ptr视为常量字符串。

因此它也会在此代码中给出分段错误..

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

但是,你可以这样做::

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

答案 2 :(得分:0)

char * const pstr = "abcd"

这是指针初始化。所以&#34; abcd&#34;存储在Memory的代码部分。你不能修改内存的代码部分。它是只读存储器。所以。由于访问未经授权的内存,操作系统将在运行时生成分段错误。

char pstr[]="abcd";

现在,&#34; abcd&#34;存储在数据部分,以便您可以修改。

答案 3 :(得分:0)

由数组初始化的差异b / w字符串和由指针初始化的字符串是指针字符串无法修改。原因是指针字符串存储在代码存储器中,数组字符串存储在堆栈中(如果是全局的则存储在堆中)阵列)

相关问题