简体   繁体   中英

allocating memory for a structure

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 */

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 .

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM