gpt4 book ai didi

c - 用指针修改字符串

转载 作者:行者123 更新时间:2023-11-30 16:45:04 25 4
gpt4 key购买 nike

这两个代码要改变字符2在角色'4'

int main(int argc, char *argv[]){   
char *s = "hello";
*(s+2)='4';
printf( "%s\n",s);
return 0;
}

当我运行这个时,我遇到段错误:

int main(int argc, char *argv[]){   
char *s = argv[1];
*(s+2)='4';
printf( "%s\n",s);
return 0;
}

我知道还有其他方法可以做到这一点。这两个程序有什么区别?

最佳答案

在第一种情况下,您面临 undefined behaviour尝试修改字符串文字。段错误是 UB 的常见副作用之一。

在您的代码中,

 char *s = "hello";

本质上是将字符串文字的起始地址“hello”放入s中。现在,您是否想要修改*s(或*(s+n))的内容,前提是n不超出范围),它实际上会尝试修改该字符串文字。通常,字符串文字存储在只读存储器中,通常不允许修改。引用自 C11,第 §6.4.5 章,字符串文字(强调我的)

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

但是,在第二种情况下,你正在做

 char *s = argv[1];

它将argv[1]的值放入s中。现在,s 指向 argv[1] 包含的字符串。这里,argv[1](或者一般来说,argv[n])的内容不是只读的,而是可以修改的。因此,使用 *s (或 *(s+n),前提是 n 不超出范围),您可以修改内容.

这种情况是定义的行为,因为根据§5.1.2.2.2,程序启动

The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

因此,第二种情况是使用argv[n]时的特殊情况,它符合C标准规则,可修改。

关于c - 用指针修改字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243953/

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