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

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

问题描述

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

I have a C struct defined as follows:

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

当我创建了一个访客变量并使用以下初始化它:

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 不能用于初始化成员变量的误差字符名称[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 和朋友的结构。在这种情况下,你需要处理 \\ 0 终止。

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(mike.name, guest_name, 20);
mike.name[19] = 0; // ensure termination

如果您有 \\ 0 结尾的字符串,你也可以使用的strcpy ,但因为名称的大小为20,我建议函数strncpy

If you have \0 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天全站免登陆