0

Is there a way to declare a structure with default initalisation values?

I have a header file which defines a structur like this:

typedef struct struc_s
{
    size_t cost const = 2000;
    size_t dmg const = 100;
    size_t def const = 100;
    size_t hull const = 1500;
    size_t shield const = 300;
    size_t capacity const = 2;
    size_t destruc const = 10;
} struc_t;

But this ofcourse doesn't work.

I would also be fine with a way of declaring a var of type struc_t in this header file. But as I remember right. I would have to decalre it in the c file as extern

What I want to do is every where where this header is included i want to be able to do var = struc_s.dmg and and the result should be that var holds the value 100. But I dont want to declare struc_s anywhere else then in the header. Is there a way to archive this behavior?

4

2 回答 2

1

不是你想要的方式。

当您执行 typedef 时,您正在定义内存区域的形状,这是一个不同于分配和填充它的过程。

一个可能的替代方案:

typedef struct 
{
    size_t cost;
    size_t dmg;
    size_t def;
    size_t hull;
    size_t shield;
    size_t capacity;
    size_t destruc;
} struc_t;


#ifndef DEFAULT_STRUC_VALUES_DEFINED
#define DEFAULT_STRUC_VALUES_DEFINED 

const struc_t DEFAULT_STRUC = {
    .cost = 2000,
    .dmg = 100,
    .def = 100,
    .hull = 1500,
    .shield = 300,
    .capacity = 2,
    .destruc = 10
};
#endif

然后当你想创建一个新的时:

struc_t *new_struc = malloc(sizeof(struc_t));
memcpy(new_struc, DEFAULT_STRUC, sizeof(struc_t));

作为旁注,您使用size_t结构成员是否有原因?它本质上没有任何问题,但它可能会因平台而异。

于 2013-10-16T18:51:04.303 回答
1
typedef struct struc_s
{
int a;
int b;    
}s; 

这是类型定义,不是对象的声明。您可以在声明对象时进行初始化。

当可以给出连续成员时,使用 C89 样式的初始化程序。

s obj={1,2}; 

对于不连续或乱序的成员列表,可以使用指定的初始化样式

s obj={.a=1,.b=2};  

     or

s obj={.b=2,.a=1};

第三种方法是复制相同类型的现有对象的值

s obj1=obj;
于 2013-10-16T18:49:53.133 回答