Dereferencing pointer to incomplete type

点点圈 提交于 2019-12-20 07:24:17

问题


I am getting the following error from this piece of code, I am new to C and learning as I go along!

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

Main .C file

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 file

typedef struct bridge bridge_t;

Anybody have any ideas??


回答1:


To avoid the error you mention you should move this:

struct bridge
{
  int s;
};

to bridge.h.

Currently it is declared local to the module (translation unit) bridge.c and so its members are not know to the outside world.


Alternativly, if you want to hide the internals of struct bridge, you need to add a getter and a setter function to the module bridge.c for each member which you want to access from the outside like for example so:

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

So the snippet from your main.c would then look like:

#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));


来源:https://stackoverflow.com/questions/18609940/dereferencing-pointer-to-incomplete-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!