2016-05-30 65 views
-1

我试图获取在不同的源文件(other.c)中定义的结构的大小以使其隐藏。获取隐藏结构的大小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’ 

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

+6

你不能这样做。如果你想'main.c'能够在'struct X'的实例(而不是指针)上运行,你需要在头文件中定义。 –

+0

'sizeof'在编译时进行评估。如果'struct'不可见,则无法调整大小。 –

+7

没有'struct x_t',只有'x_t'或'struct X'这样的事情 – user3078414

回答

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; 
} 
+1

解决方案确实是一组获取者和制定者! –