c - 如何将 char* 复制到 char[][]

标签 c arrays string

开始之前,让我向您展示我的代码:

int     main(int argc, char *argv[])
{                  
  t_arbre       *node;
  char          str[3][1];

  &(*(str[0])) = strdup("1"); //lvalue required as left operand of assignment
  str[1] = strdup("2"); //incompatible types when assigning to type ‘char[1]’ from type ‘char *’
  str[2] = strdup("3");
  if ((node = malloc(sizeof(t_arbre))) == NULL)
    {
      printf("Error: malloc in the main function failed\n");
      return (-1);
    }
  create_node(node, str);
  return (0);
}

所以,如您所见,我目前正在使用 C 语言工作。我正在尝试将 (char*) 分配给 (char[3][1])。否则编译器会抛出错误:

incompatible types when assigning to type ‘char[1]’ from type ‘char *’

当我尝试通过以下方式分配时:

str[2] = strdup("2"); 

我知道如果我声明一个这样的字符串

char str[5];

然后尝试使用例如 strdup() 函数为其分配一个字符串,它可能会给我带来同样的错误。但是在这种情况下,我知道我可以像这样“取消引用”它:

str[0] 

这会给我一个(char)变量。鉴于我希望它存储一个字符串。我必须使用“&”字符将其“转换”为 (char*)。这会给我

&str[0]

在这种情况下,它会起作用。因为我有一个指向第一个字符的指针。 通过这样做,我将能够将 (char*) 复制到 (char[])。

否则,在我给你提供的上面的代码中,我想将一个 (char*) 复制到一个 (char[3][1]) (别问我为什么,解释起来有点长哈哈) 正如您所看到的,我尝试了解决错误的方法,例如

str[2] = strdup("2");

它向我抛出此错误消息

incompatible types when assigning to type ‘char[1]’ from type ‘char *’

就这样

&(*(str[0])) = strdup("1"); //or &(*(str[0]))

它向我抛出此错误消息

lvalue required as left operand of assignment

有谁能告诉我如何将 (char*) 复制到 (char[][]) 中? 或者只是不可能做我想做的事? 我英语说得不太好,希望我用了正确的术语。

谢谢:)

最佳答案

  • 你不能分配给不打算分配的东西,这就是“左值需要作为分配的左操作数”告诉你的,因为你正在使用的东西的地址&,本质上只是一个值,而不是可以存储某些内容(例如变量),然后尝试分配给它的地方。
  • char* 不是 char[],这就是不兼容类型错误的原因。
  • C 数组不支持赋值。
  • 不要忘记,在 C 语言中,数组从索引 0 开始,因此长度为 3 的数组中的最后一个有效索引是 2(例如 arr[2]),而不是 3。<

使用strcpy()而是将字符串复制到数组中:

char str[3][2]; // must allow space for the null terminator
strcpy(str[0], "1");
strcpy(str[1], "2");
strcpy(str[2], "3");

或者使用指针数组和 strdup() :

char *str[3];
str[0] = strdup("1");
...

如果您这样做,请不要忘记在完成后释放它们,因为 strdup() 会分配内存,例如

// free one pointer from the array:
free(str[0]);
// or if you have allocated to every value in the array:
size_t arr_len = sizeof(str) / sizeof(*str);
for (size_t n = 0; n < arr_len; ++n)
    free(str[n]);

关于c - 如何将 char* 复制到 char[][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727250/

相关文章:

c - 警告 : format ‘%s’ expects argument of type ‘char *’ , 但参数 2 的类型为 ‘int’ 使用 argv

java - 通过串行连接将minecraft插件连接到arduino

arrays - Excel - 数组公式跳过空单元格

java - 将字符串转换为多个字符串

python - 以 Unicode 代码的形式打印字符串

在一个字节中转换两个 ASCII 十六进制字符(两个 ASCII 字节)

c - 手动加载编译后的代码

php - 处理在 MySQL 中存储为 JSON 对象的数据

C++ 查找函数返回类型

java - 非常大的字符串出现 StringIndexOutOfBoundsException