【发布时间】:2021-03-09 17:32:50
【问题描述】:
我正在尝试将字符串复制到结构中,但它不显示任何内容。你能帮我找出问题所在吗?
typedef struct{
long tipo;
char *buffer;
}msg;
msg mess;
strcpy(mess.buffer,"hello");
printf("%s\n",mess.buffer);
【问题讨论】:
-
char *buffer是一个没有分配内存的指针。试试mess.buffer = "hello";(文本不可修改)或mess.buffer = strdup("hello"); -
请注意,
strdup是非标准的(在 C23 标准之前)。如果它不可用,您可以使用strlen、malloc和strcpy。在这两种情况下,当您不再需要为字符串分配的内存时,都应该使用free。 -
@Bodo 我同意,但我认为 memcpy 会比 strcpy 更快,因为您不需要检查
'\0',感谢strlen,您已经得到了它。我认为 OP 正在寻找一个 char 数组,他正在使用它的结构。 -
请注意,结构无关紧要。您必须首先了解问题所在:
char *buffer; strcpy(buffer, "hello");