使用 char 数组进行 C 结构初始化 [英] C struct initialization with char array
问题描述
我有一个 C 结构定义如下:
I have a C struct defined as follows:
struct Guest {
int age;
char name[20];
};
当我创建一个 Guest
变量并使用以下内容对其进行初始化时:
When I created a Guest
variable and initialized it using the following:
int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = {guest_age, guest_name};
我收到关于第二个参数初始化的错误,它告诉我 guest_name
不能用于初始化成员变量 char name[20]
.
I got the error about the second parameter initialization which tells me that guest_name
cannot be used to initialize member variable char name[20]
.
我可以这样做来初始化所有:
I could do this to initialize all:
struct Guest mike = {guest_age, "Mike"};
但这不是我想要的.我想通过变量初始化所有字段.如何在 C 中做到这一点?
But this is not I want. I want to initialize all fields by variables. How to do this in C?
推荐答案
mike.name
是 struct 内 20 字节的保留内存.guest_name
是指向另一个内存位置的指针.通过尝试将 guest_name
分配给结构的成员,您尝试了一些不可能的事情.
mike.name
is 20 bytes of reserved memory inside the struct. guest_name
is a pointer to another memory location. By trying to assign guest_name
to the struct's member you try something impossible.
如果必须将数据复制到结构中,则必须使用 memcpy
和朋友.在这种情况下,您需要处理