gpt4 book ai didi

c - 为什么这个小的 C 程序会崩溃?

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:43 24 4
gpt4 key购买 nike

程序是:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a="abc",*ptr;
ptr=a;
ptr++;
*ptr='k';
printf("%c",*ptr);
return 0;
}

问题出在

*ptr='k';  

行,当我删除它时程序正常工作。但我想不通原因。

最佳答案

问题是因为您正试图更改字符串文字 "abc" :

char *a="abc",*ptr;
ptr=a; // ptr points to the 'a'.
ptr++; // now it points to the 'b'.
*ptr='k'; // now you try to change the 'b' to a 'k'.

这是未定义的行为。该标准明确指出,您不得根据 C99 的 6.4.5 String literals 部分更改字符串文字:

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 *a="abc",*ptr;

与:

char a[]="abc",*ptr;

因为这会将字符串文字复制到可以安全修改的地方。

关于c - 为什么这个小的 C 程序会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8784099/

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