当我们尝试修改字符串常量时会发生什么? [英] What should happen, when we try to modify a string constant?
问题描述
#include<stdio.h>
#include<string.h>
int main()
{
int i, n;
char *x="Alice"; // ....... 1
n = strlen(x); // ....... 2
*x = x[n]; // ....... 3
for(i=0; i<=n; i++)
{
printf("%s ", x);
x++;
}
printf("\n");
return 0;
}
字符串常量不能修改.在上面的代码中*x 表示'A'.在第 3 行,我们试图修改一个字符串常量.写那个语句正确吗?当我在 Linux 上运行此代码时,我遇到了分段错误.但是在 www.indiabix.com 上,他们给出了答案:
String constant cannot be modified. In the above code *x means 'A'. In line 3 we are trying to modify a string constant. Is it correct to write that statement? When I run this code on Linux, I got segmentation fault. But on www.indiabix.com, they have given answer:
如果你在 windows 平台上用 Turbo C 编译并执行这个程序,它会给出 lice ice ce e 在其他平台上可能给出不同的输出(取决于编译器和机器).本站提供的在线 C 编译器将给出 Alice lice ice ce e 作为输出(它在 Linux 平台上运行).
If you compile and execute this program in windows platform with Turbo C, it will give lice ice ce e It may give different output in other platforms (depends upon compiler and machine). The online C compiler given in this site will give Alice lice ice ce e as output (it runs on Linux platform).
推荐答案
你的分析是正确的.线
*x = x[n];
正在尝试修改字符串文字,因此这是未定义的行为.
is trying to modify a string literal, so it's undefined behavior.
顺便说一句,我检查了您链接的网站.仅仅浏览了两分钟,我已经发现了多个不正确的代码示例(仅举几例,使用 gets
,使用 char
(不是 int
>) 来分配 getchar
等的返回值),所以我的建议是不要使用它.
BTW, I checked the website that you linked. Just browsing it for two minutes, I've already found multiple incorrect code samples (to name a few, using gets
, using char
(not int
) to assign return value of getchar
, etc), so my suggestion is don't use it.
这篇关于当我们尝试修改字符串常量时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!