为什么我不能编辑一个char *一个char? [英] Why can't I edit a char in a char*?

查看:142
本文介绍了为什么我不能编辑一个char *一个char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个非常简单的例子。它使用的是Mac OS X(雪豹)的gcc编译罚款。在运行时,它输出总线错误:10.这里发生了什么。

 的char * A =ABC;
一个[0] ='c'的;


解决方案

您code组 A 的指针ABC ,它是不能被修改文字的数据。当你的code违反了这个限制,并试图修改数值出现总线错误。

试试这个来代替:

 的char a [] =ABC;
一个[0] ='c'的;

这将创建一个字符数组(在你的程序的正常数据空间),而拷贝的字符串文字到您的数组的内容。的现在的,你应该没有问题作出更改。

Below is an exceedingly simple example. It compiles fine using gcc on Mac OS X (Snow Leopard). At runtime it outputs Bus error: 10. What's happening here?

char* a = "abc";
a[0] = 'c';

解决方案

Your code sets a to a pointer to "abc", which is literal data that can't be modified. The Bus error occurs when your code violates this restriction, and tries to modify the value.

try this instead:

char a[] = "abc";
a[0] = 'c';

That creates a char array (in your program's normal data space), and copies the contents of the string literal into your array. Now you should have no trouble making changes to it.

这篇关于为什么我不能编辑一个char *一个char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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