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

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

问题描述

以下code产生在我的系统分割故障。我想不通为什么。任何帮助将是AP preciated。

 #包括LT&;&stdio.h中GT;
诠释主(){
    字符* A =ABC;
    * A ='C';
    的printf(%C \\ n,*一);
    返回0;
}


解决方案

标准中明确列出了§J.2这是未定义的行为:


  

- 该程序试图修改
  字符串(6.4.5)


如果你想将它复制到本地数组,这样做:

 的char a [] =ABC;

A 是在栈上的数组,你可以自由地修改它。

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\n", *a);
    return 0;
}

解决方案

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

— 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 is an array on the stack, and you can modify it freely.

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

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