当我们能或不能修改字符串字面 [英] When we can or cannot modify String Literals
本文介绍了当我们能或不能修改字符串字面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<stdio.h>
int main ()
{
char *s="FIGHT" ;
printf("\n Whole string is %s ", s ); // Printing FIGHT -- this is fine
s[0]='L' ;
printf ("\n Now whole string is %s", s ); // Printing LIGHT -- My Question is how string literal constant is getting modified when it is being stored in read only memory .
}
以上code是我的系统上正常工作。
Above Code is working fine on my system.
推荐答案
TL; DR - 不要
TL;DR -- Never.
任何试图修改字符串调用未定义行为。
Any attempt to modify a string literal invokes undefined behavior.
要引用 C11
标准,章§6.4.5,的字符串字面的
To quote the C11
standard, chapter §6.4.5, String literals
[...]。如果程序试图修改这样的阵列,该行为是
不确定的。
[...]. If the program attempts to modify such an array, the behavior is undefined.
§的上面code正在我的系统上精的
是的,欢迎的未定义的行为,其中包括世界上的工作作为(错误地)预计的
Yes, welcome to the world of undefined behavior, which includes working as (wrongly) expected.
这篇关于当我们能或不能修改字符串字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文