为什么 C 的 strcpy 使用双索引数组会失败?
下面的代码似乎出现了段错误,我不明白为什么。
#include <string.h>
static char src[] = "aaa";
int main()
{
char* target[2] = {"cccc","bbbbbbbbbb"};
strcpy(target[1],src);
return 0;
}
The following code seems to segfault and I cannot figure out why.
#include <string.h>
static char src[] = "aaa";
int main()
{
char* target[2] = {"cccc","bbbbbbbbbb"};
strcpy(target[1],src);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
target[1]
是指向"bbbbbbbbbb"
的指针,并且不允许修改字符串常量。这是未定义的行为。这与:
我认为您可能将其与:
which有效相混淆,因为它创建了一个允许您修改的数组。但是你的给你的是:
一个指针数组,所有这些都指向不可修改的内存。
如果您尝试一下:
您会发现它可以工作,因为
target[1]
现在指向可修改的t1
。Because
target[1]
is a pointer to"bbbbbbbbbb"
and you are not allowed to modify string constants. It's undefined behaviour.It's no different to:
I think you may be confusing it with:
which is valid since it creates an array that you are allowed to modify. But what yours gives you:
is an array of pointers, all of which point to non-modifiable memory.
If you were to try:
you would find that it works since
target[1]
now points tot1
, which is modifiable.