C语言 C 结构体初始化与字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18966979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:32:21  来源:igfitidea点击:

C struct initialization with char array

cstructchar

提问by tonga

I have a C struct defined as follows:

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

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

When I created a Guestvariable 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_namecannot 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 中做到这一点?

回答by Scolytus

mike.nameis 20 bytes of reserved memory inside the struct. guest_nameis a pointer to another memory location. By trying to assign guest_nameto the struct's member you try something impossible.

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

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

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

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

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

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

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

回答by Steve Howard

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

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

Instead, you'll need to use strncpyor 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::stringin preference to char[].

您已将此问题标记为 C++,因此我想指出,在这种情况下,您几乎应该始终std::string优先使用char[].

回答by Daniel

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.

正如您可能怀疑的那样,这不适用于从堆栈分配的结构。