C 结构体初始化与字符数组 [英] C struct initialization with char array

查看:26
本文介绍了C 结构体初始化与字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 是结构体内部 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 和朋友.在这种情况下,您需要处理 终止符.

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

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

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

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

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

这篇关于C 结构体初始化与字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆