当我们能够或不能修改String Literals时

时间:2015-07-27 17:16:25

标签: c string 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 .
}

以上代码在我的系统上正常运行。

1 个答案:

答案 0 :(得分:6)

TL; DR - 从不。

任何修改字符串文字的尝试都会调用undefined behavior

引用C11标准,章节§6.4.5,字符串文字

  

[...]。如果程序试图修改这样的数组,则行为是   未定义。

§“以上代码在我的系统上工作正常”

是的,欢迎来到未定义行为的世界,其中包括工作为(错误的)预期

相关问题