使用char数组进行C struct初始化

时间:2022-07-25 18:54:27

I have a C struct defined as follows:

我有一个C结构定义如下:

struct Guest {
   int age;
   char name[20];
};

When I created a Guest variable and initialized it using the following:

当我创建一个Guest变量并使用以下内容对其进行初始化时:

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = {guest_age, guest_name};

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].

我得到了关于第二个参数初始化的错误,它告诉我guest_name不能用于初始化成员变量char name [20]。

I could do this to initialize all:

我可以这样做来初始化所有:

struct Guest mike = {guest_age, "Mike"};

But this is not I want. I want to initialize all fields by variables. How to do this in C?

但这不是我想要的。我想按变量初始化所有字段。如何在C中执行此操作?

3 个解决方案

#1


15  

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.

mike.name是struct中20个字节的保留内存。 guest_name是指向另一个内存位置的指针。通过尝试将guest_name分配给struct的成员,您尝试了一些不可能的事情。

If you have to copy data into the struct you have to use memcpy and friends. In this case you need to handle the \0 terminator.

如果必须将数据复制到结构中,则必须使用memcpy和朋友。在这种情况下,您需要处理\ 0终止符。

memcpy(mike.name, guest_name, 20);
mike.name[19] = 0; // ensure termination

If you have \0 terminated strings you can also use strcpy, but since the name's size is 20, I'd suggest strncpy.

如果您有\ 0终止字符串,您也可以使用strcpy,但由于名称大小为20,我建议使用strncpy。

strncpy(mike.name, guest_name, 19);
mike.name[19] = 0; // ensure termination

#2


4  

mike.name is a character array. You can't copy arrays by just using the = operator.

mike.name是一个字符数组。您只能使用=运算符来复制数组。

Instead, you'll need to use strncpy or something similar to copy the data.

相反,您需要使用strncpy或类似的东西来复制数据。

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = { guest_age };
strncpy(mike.name, guest_name, sizeof(mike.name) - 1);

You've tagged this question as C++, so I'd like to point out that in that case you should almost always use std::string in preference to char[].

你已经将这个问题标记为C ++,所以我想指出在这种情况下你应该几乎总是使用std :: string而不是char []。

#3


-1  

You can statically allocate a struct with a fixed char[] array in C. For example, gcc allows the following:

您可以在C中静态分配带有固定char []数组的结构。例如,gcc允许以下内容:

#include <stdio.h>

typedef struct {
    int num;
    char str[];
} test;

int main(void) {
    static test x={.num=sizeof("hello"),.str="hello"};

    printf("sizeof=%zu num=%d str=%s\n",sizeof(x),x.num,x.str);
    return 0;
}

And it does the right thing (though beware of the sizeof(x): it returns 4 on my machine; not the length of the total statically allocated memory).

它做的是正确的(虽然要注意sizeof(x):它在我的机器上返回4;而不是静态分配的总内存的长度)。

This does not work for structs allocated from the stack, as you might suspect.

对于从堆栈分配的结构,这不起作用,您可能会怀疑。

#1


15  

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.

mike.name是struct中20个字节的保留内存。 guest_name是指向另一个内存位置的指针。通过尝试将guest_name分配给struct的成员,您尝试了一些不可能的事情。

If you have to copy data into the struct you have to use memcpy and friends. In this case you need to handle the \0 terminator.

如果必须将数据复制到结构中,则必须使用memcpy和朋友。在这种情况下,您需要处理\ 0终止符。

memcpy(mike.name, guest_name, 20);
mike.name[19] = 0; // ensure termination

If you have \0 terminated strings you can also use strcpy, but since the name's size is 20, I'd suggest strncpy.

如果您有\ 0终止字符串,您也可以使用strcpy,但由于名称大小为20,我建议使用strncpy。

strncpy(mike.name, guest_name, 19);
mike.name[19] = 0; // ensure termination

#2


4  

mike.name is a character array. You can't copy arrays by just using the = operator.

mike.name是一个字符数组。您只能使用=运算符来复制数组。

Instead, you'll need to use strncpy or something similar to copy the data.

相反,您需要使用strncpy或类似的东西来复制数据。

int guest_age = 30;
char guest_name[20] = "Mike";
struct Guest mike = { guest_age };
strncpy(mike.name, guest_name, sizeof(mike.name) - 1);

You've tagged this question as C++, so I'd like to point out that in that case you should almost always use std::string in preference to char[].

你已经将这个问题标记为C ++,所以我想指出在这种情况下你应该几乎总是使用std :: string而不是char []。

#3


-1  

You can statically allocate a struct with a fixed char[] array in C. For example, gcc allows the following:

您可以在C中静态分配带有固定char []数组的结构。例如,gcc允许以下内容:

#include <stdio.h>

typedef struct {
    int num;
    char str[];
} test;

int main(void) {
    static test x={.num=sizeof("hello"),.str="hello"};

    printf("sizeof=%zu num=%d str=%s\n",sizeof(x),x.num,x.str);
    return 0;
}

And it does the right thing (though beware of the sizeof(x): it returns 4 on my machine; not the length of the total statically allocated memory).

它做的是正确的(虽然要注意sizeof(x):它在我的机器上返回4;而不是静态分配的总内存的长度)。

This does not work for structs allocated from the stack, as you might suspect.

对于从堆栈分配的结构,这不起作用,您可能会怀疑。