得到隐藏结构C的大小

时间:2016-05-30 18:45:51

标签: c

我试图获取在不同源文件(other.c)中定义的结构的大小以使其隐藏。

在other.h:

typedef struct X x_t;

在other.c:

struct X{
int y;
int z;
};

现在我想在main.c中获得这个结构的大小。

#include "other.h"

int main(){
    x_t *my_x;
    my_x = malloc(sizeof(struct x_t));
    return 0;}

但是这给了我以下错误:

error: invalid application of ‘sizeof’ to incomplete type ‘struct x_t’

任何人都可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:3)

隐藏struct的目的是仔细控制它们的构造,破坏和访问内容。

必须提供构造,破坏,获取内容和设置内容的函数,以使隐藏的struct有用。

以下是.h和.c文件的示例:

other.h:

typedef struct X x_t;

x_t* construct_x(void);

void destruct_x(x_t* x);

void set_y(x_t* x, int y);

int get_y(x_t* x);

void set_z(x_t* x, int z);

int get_z(x_t* x);

other.c:

struct X {
   int y;
   int z;
};


x_t* construct_x(void)
{
   return malloc(sizeof(x_t));
}

void destruct_x(x_t* x)
{
   free(x);
}

void set_y(x_t* x, int y)
{
   x->y = y;
}

int get_y(x_t* x)
{
   return x->y;
}

void set_z(x_t* x, int z)
{
   x->z = z;
}


int get_z(x_t* x)
{
   rteurn x->z;
}
相关问题