我写了两段代码,我打算有相同的输出,但令人困惑的是,它们有不同的输出。
第一段代码:
#include<stdio.h>
int main(){
char a[]="abc";
char *p=&a;
char c=++(*p);
printf("%c,%s\n",c,p);
return 0;
}
输出如下:
b,bbc
第二段代码:
#include<stdio.h>
int main(){
char *p="abc";
char c=++(*p);
printf("%c,%s\n",c,p);
return 0;
}
哪些输出:
a,abc
阻止字符串第一个字符递增的第二段代码发生了什么?
最佳答案
第二个示例尝试更改未定义行为的字符串文字。你通常会因为这样做而崩溃,但在你的情况下,它似乎只是被“忽略”了。
char *p="abc"; char c=++(*p); /* Illegal to change *p. */
标准报价:
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.
关于c - 修改和打印字符串不会产生预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979711/