在c中修改char指针的值会产生段错误 [英] Modifying value of char pointer in c produces segfault

查看:27
本文介绍了在c中修改char指针的值会产生段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在我的系统上产生分段错误.我不知道为什么.任何帮助,将不胜感激.

The following code produces a segmentation fault on my system. I can't figure out why. Any help would be appreciated.

#include<stdio.h>
int main() {
    char * a = "abc";
    *a = 'c';
    printf("%c
", *a);
    return 0;
}

推荐答案

标准在 §J.2 中明确将此列为未定义行为:

The standard explicitly lists this as undefined behavior in §J.2:

——程序试图修改一个字符串文字(6.4.5)

— The program attempts to modify a string literal (6.4.5)

如果要将其复制到本地数组中,请执行以下操作:

If you want to copy it into a local array, do:

char a[] = "abc";

a是栈上的数组,可以自由修改.

a is an array on the stack, and you can modify it freely.

这篇关于在c中修改char指针的值会产生段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆