结构用C与初始值 [英] structs in C with initial values
本文介绍了结构用C与初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个用C与初始值如下的结构:
I want to create a structure in C with initial values like:
typedef struct
{
int id=0;
char* name="none";
}employee;
我知道这是不可能的,有没有办法做到这一点?
I know that is not possible, is there any way to do this?
推荐答案
您不能做这样
使用替代以下
typedef struct
{
int id;
char* name;
}employee;
employee emp = {
.id = 0
.name = "none"
};
您可以使用宏来的确定和初始化您的实例。这要定义新的实例并初始化它每次都会让easiier给你。
You can use macro to define and initialize your instances. this will make easiier to you each time you want to define new instance and initialize it.
typedef struct
{
int id;
char* name;
}employee;
#define INIT_EMPLOYEE(X) employee X = {.id = 0, .name ="none"}
和在当你需要定义与员工类型的新实例,您的code,你只需要调用这个宏这样的:
and in your code when you need to define new instance with employee type, you just call this macro like:
INIT_EMPLOYEE(emp);
这篇关于结构用C与初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文