该计划是:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *a="abc",*ptr;
ptr=a;
ptr++;
*ptr='k';
printf("%c",*ptr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题在于
*ptr='k';
Run Code Online (Sandbox Code Playgroud)
线,当我删除它程序正常工作.但我无法弄清楚原因.
问题是因为您尝试使用以下命令更改字符串文字"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'.
Run Code Online (Sandbox Code Playgroud)
这是未定义的行为.该标准明确声明您不允许6.4.5 String literals
根据C99的部分更改字符串文字:
如果这些数组的元素具有适当的值,则这些数组是否不同是未指定的.如果程序试图修改此类数组,则行为未定义.
它会如果你更换工作:
char *a="abc",*ptr;
Run Code Online (Sandbox Code Playgroud)
有:
char a[]="abc",*ptr;
Run Code Online (Sandbox Code Playgroud)
因为它将字符串文字复制到一个可以安全修改的地方.
归档时间: |
|
查看次数: |
288 次 |
最近记录: |