scanf 转换为指针

发布于 2025-01-14 11:24:13 字数 173 浏览 4 评论 0原文

我有这样的代码:

char *ps = "hello";
scanf("%s", ps);

我想写一个字符串,让我们假装“a”,到指针而不使用数组。尝试将字符串扫描到 ps 中会导致错误被信号 10 中断:SIGBUS。我很高兴听到对这种行为的解释。

I have this code:

char *ps = "hello";
scanf("%s", ps);

I want to write a string, let's pretend "a", to pointer without using an array. Trying to scanf a string into ps causes error interrupted by signal 10: SIGBUS. I'd be happy to hear an explanation for such a behavior.

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

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

发布评论

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

评论(1

睡美人的小仙女 2025-01-21 11:24:13

指针指向字符串文字

char *ps = "hello";

因此此调用

scanf("%s", ps);

尝试更改字符串文字。

您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字)

7 未指定这些数组是否不同,只要它们的
元素具有适当的值。 如果程序尝试
修改这样的数组,行为未定义

The pointer points to a string literal

char *ps = "hello";

So this call

scanf("%s", ps);

tries to change a string literal.

You may not change string literals. Any attempt to change a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined

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