为什么我无法编辑 char* 中的字符?

发布于 2024-12-05 14:02:44 字数 140 浏览 0 评论 0原文

下面是一个非常简单的例子。它在 Mac OS X (Snow Leopard) 上使用 gcc 可以正常编译。在运行时它输出总线错误:10.这里发生了什么?

char* a = "abc";
a[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';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

娇妻 2024-12-12 14:02:44

您的代码将 a 设置为指向 "abc" 的指针,这是无法修改的文字数据。当您的代码违反此限制并尝试修改该值时,就会发生总线错误。

尝试这样做:

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

创建一个 char 数组(在程序的正常数据空间中),并将字符串文字的内容复制到数组中。 现在您应该可以毫无困难地对其进行更改。

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.

筑梦 2024-12-12 14:02:44

您正在尝试修改字符串常量。使用这个代替:

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

You are trying to modify a string constant. Use this instead:

char a[] = "abc";
a[0] = 'c';
何处潇湘 2024-12-12 14:02:44

char* a = "abc";

依赖于从 const char[](字符串文字的类型)到 char* 的危险隐式转换。 (在 C++ 中,这种转换已被弃用十多年了。不过,我不了解 C。)

不得更改字符串文字。

This

char* a = "abc";

relies on a dangerous implicit conversion from const char[] (the type of a string literal) to char*. (In C++ this conversion has been deprecated for more than a decade. I don't know about C, though.)

A string literal must not be altered.

泪眸﹌ 2024-12-12 14:02:44

char *str = "string"; 在这种情况下,它被视为只读文字。它类似于编写 const char *str = "string"。也就是说,指针str指向的值是一个常量。尝试编辑将导致总线错误。

char *str = "string"; In such a case it is treated as a read only literal. It is similar to writing const char *str = "string". Which is to say that the value pointed to by the pointer str is a constant. Trying to edit will result in BUS ERROR.

愿得七秒忆 2024-12-12 14:02:44

char *a = "abc" 是存储在 ELF 二进制文件的 .data 部分中的常量字符串。您不允许修改此内存,如果您这样做,在某些情况下会发生未定义的行为,它不会给出错误,但不会修改内存,在您的情况下,您会收到总线错误,因为您正在尝试访问通常无法访问的内存(例如写作目的)。

char *a = "abc" is a constant string stored in the .data section of an ELF binary. You are not allowed to modify this memory and if you do you incur undefined behavior in some cases it will give no error but not modify the memory in your case you get a bus error because you are attempting to access memory that you normally cannot (for writing purposes).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文