gpt4 book ai didi

c - 修改 char * const pstr = "abcd"时出现段错误;

转载 作者:行者123 更新时间:2023-11-30 18:53:23 25 4
gpt4 key购买 nike

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 行遇到段错误(核心转储)...所以我编写了下一个代码

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

}

但我不知道为什么???

最佳答案

char * const pstr = "abcd"; 

pstr 是指向 char 的常量指针,您无法正确修改 pstr ,但 "abcd" > 是一个字符串迭代。并且您无法修改字符串文字。

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

关于c - 修改 char * const pstr = "abcd"时出现段错误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com