为什么C的strcpy会因双重索引数组而失败?

时间:2022-01-04 21:43:16

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;
}

1 个解决方案

#1


11  

Because target[1] is a pointer to "bbbbbbbbbb" and you are not allowed to modify string constants. It's undefined behaviour.

因为target [1]是指向“bbbbbbbbbb”的指针,所以不允许修改字符串常量。这是未定义的行为。

It's no different to:

它与以下内容没有什么不同:

char *x = "bbb";
x[0] = 'a';

I think you may be confusing it with:

我想你可能会混淆它:

char x[] = "bbb";
x[0] = 'a';

which is valid since it creates an array that you are allowed to modify. But what yours gives you:

这是有效的,因为它创建了一个允许您修改的数组。但是你的东西给了你:

char* target[2] = {"cccc","bbbbbbbbbb"};

is an array of pointers, all of which point to non-modifiable memory.

是一个指针数组,所有这些都指向不可修改的内存。

If you were to try:

如果您尝试:

char t0[] = "cccc";
char t1[] = "bbbbbbbbbb";
char* target[2] = {t0, t1};
strcpy(target[1],src);

you would find that it works since target[1] now points to t1, which is modifiable.

你会发现它有效,因为目标[1]现在指向t1,这是可修改的。

#1


11  

Because target[1] is a pointer to "bbbbbbbbbb" and you are not allowed to modify string constants. It's undefined behaviour.

因为target [1]是指向“bbbbbbbbbb”的指针,所以不允许修改字符串常量。这是未定义的行为。

It's no different to:

它与以下内容没有什么不同:

char *x = "bbb";
x[0] = 'a';

I think you may be confusing it with:

我想你可能会混淆它:

char x[] = "bbb";
x[0] = 'a';

which is valid since it creates an array that you are allowed to modify. But what yours gives you:

这是有效的,因为它创建了一个允许您修改的数组。但是你的东西给了你:

char* target[2] = {"cccc","bbbbbbbbbb"};

is an array of pointers, all of which point to non-modifiable memory.

是一个指针数组,所有这些都指向不可修改的内存。

If you were to try:

如果您尝试:

char t0[] = "cccc";
char t1[] = "bbbbbbbbbb";
char* target[2] = {t0, t1};
strcpy(target[1],src);

you would find that it works since target[1] now points to t1, which is modifiable.

你会发现它有效,因为目标[1]现在指向t1,这是可修改的。