获得隐藏结构的C尺寸 [英] get size of hidden struct C

查看:90
本文介绍了获得隐藏结构的C尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让在不同的源文件(other.c)来掩盖它定义的一个结构的大小。

I'm trying to get the size of a struct that was defined in a different source file (other.c) to keep it hidden.

在other.h:

typedef struct X x_t;

在other.c:

struct X{
int y;
int z;
};

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

Now I want in the main.c to get the size of this struct.

#include "other.h"

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

但是,这给了我以下错误:

But this gives me following error:

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

有人能帮助我吗?谢谢!

Can anybody help me? Thank you!

推荐答案

具有的全部目的隐藏结构是小心地控制他们的建筑,销毁和访问到的内容。

The whole purpose of having a hidden struct is to carefully control their construction, their destruction, and access to the contents.

函数来构造,销毁,得到的内容,并设置内容必须提供,使隐藏的结构有用的。

Functions to construct, destruct, get the contents, and set the contents have to be provided to make the hidden struct useful.

下面是一个什么样的h和.c文件可能是一个例子:

Here's an example of what the .h and .c files could be:

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:

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

这篇关于获得隐藏结构的C尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆