取消引用指向不完整类型的指针

时间:2013-09-04 09:20:30

标签: c pointers dereference incomplete-type

我从这段代码中得到以下错误,我是C的新手并且在我学习的同时学习!

cc -g -I /usr/lib/i386-linux-gnu -c anld.c
anld.c: In function ‘main’:
anld.c:379:11: error: dereferencing pointer to incomplete type

主.C文件

bridge_t *bridge_p = bridge_new();   //Create / init our bridge

bridge_p->s = server_connect(options.server_p, options.dest_port,
            options.ifname_p, options.gateway_p);

bridge .C file

struct bridge
{
  int s;
};

bridge_t *bridge_new(void)
{
  bridge_t *bridge_p;

  bridge_p = OPENSSL_malloc(sizeof *bridge_p);
  if (!bridge_p)
  {
    return NULL;
  }

  /* Initialise bridge */
  memset(bridge_p, '\0', sizeof *bridge_p);

  bridge_p->s = -1;

  return bridge_p;
}

bridge.h文件

typedef struct bridge bridge_t;

有人有任何想法吗?

1 个答案:

答案 0 :(得分:1)

为了避免您提到的错误,您应该移动它:

struct bridge
{
  int s;
};

bridge.h

目前,它被声明为模块(翻译单元)bridge.c的本地,因此其成员不了解外界。


另外,如果要隐藏struct bridge的内部,则需要为要从外部访问的每个成员添加一个getter和setter函数到模块bridge.c,例如例如:

bridge.h

typedef struct bridge bridge_t;

void brigde_s_set(bridge_t *, int);
int bridge_s_get(bridge_t *);

bridge.c

#include "bridge.h"

struct bridge
{
  int s;   
};

int brigde_s_set(bridge_t * pb, int s)
{
  pb->s = s;
}

int bridge_s_get(bridge_t * pb)
{
  return pb->s;
}

因此,您main.c的代码段将如下所示:

#include "bridge.h"

...

bridge_t * bridge_p = bridge_new();   //Create / init our bridge

bridge_s_set(bridge_p, 
  server_connect(options.server_p, options.dest_port, options.ifname_p, options.gateway_p));