tags:

views:

110

answers:

2

Hello,

gcc 4.4.4 c89

I am keep getting a "Cannot dereference to incomplete type".

However, I am sure I have my structure type complete. I return the Network_t instance that is the pointer to the allocated memory. I should be able to dereference that memory.

Many thanks for any advice,

I have this in my header file: driver.h

typedef struct Network_t Network_t;
Network_t* create_network(int id);

Implementation file driver.c

#include "driver.h"

struct Network_t {
    int id;
};

Network_t* create_network(int id)
{
    Network_t *network = malloc(sizeof *network);

    if(network) {
        network->id = id;
    }
    return network;
}

And in my main.c

#include "driver.h"

Network_t *network = NULL;
network = create_network(1);
printf("Network ID: [ %d ]\n", network->id); /* Cannot dereference pointer to incomplete type */
+10  A: 

From main.c you only have a forward declaration of struct Network_t visible. To access id from a pointer to struct Network_t you need a definition of the struct to be visible at the point at which you dereference it.

You could move the definition from driver.c to driver.h.

Charles Bailey
I would like to hide the definition of the structure. That is why I didn't put it in the header file. Is there anyway I could still do this without moving my structure definition to driver.h? Thanks.
robUK
You could provide a function to access the `id` member.
Joe D
@robUK: You can write the `struct Network_t` definition in the .c file or use a private .h file (driver-private.h) for that.
pmg
@robUK: Can you clarify your requirements? If `main.c` knows what members `struct Network_t` has and needs to access them, what are you trying to achieve by hiding the definition from `main.c` ?
Charles Bailey
@Joe D, that is what I did. Thanks.
robUK
A: 

this one works

in driver.h

#include <stdio.h>
#include<stdlib.h>
 struct Network_t{

     int id;

 };
 Network_t *create_network( int id){
     Network_t *network=(Network_t *)malloc(sizeof(network));

     if (network){
         network->id=id;
     }
      return network;

 }

in Network.cpp

#include <iostream>
#include "driver.h"
using namespace std;
int main(){

    Network_t *network=NULL;
     network=create_network(1);
     printf("Network ID:[%d]\n",network->id);
     return 0;
}

result:

Network ID:[1]
Original Post is not tagged `C++`. In `C` it is **very** unusual to have code in header files.
pmg