使用 char 数组进行 C 结构初始化

编程入门 行业动态 更新时间:2024-10-27 01:28:13
本文介绍了使用 char 数组进行 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 是 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 和朋友.在这种情况下,您需要处理 终止符.

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

更多推荐

使用 char 数组进行 C 结构初始化

本文发布于:2023-07-30 11:06:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   结构   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!