C语言开发笔记(五)字符串常量

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *str = "sting";

    strcpy(str, "hello");

    printf("%s\n", str);

    return 0;
}

代码为什么会运行错误,异常退出?

这段代码是新手常见错误之一。

定义中的字符串“sting”放在常量区,char *str只是取了"sting"在常量区的地址。

常量是分配在静态区域的,无法再进行修改,所以strcpy会导致程序异常。

猜你喜欢

转载自blog.csdn.net/Dr_Haven/article/details/82799425