rablentain
rablentain

Reputation: 6745

Why do I get "dereferencing pointer to incomplete type"?

I do not understand why I get this error. I tried google but i think that my code seems right... In main I have this:

Database *database;
database = (Database *)malloc(db_sizeOfStruct());

database->key = "word";

And in my module file I have this:

typedef struct database {
     char key;
     char value;
     struct database *next;
} Database;

int db_sizeOfStruct() {
    return sizeof(struct database);
}

The compiler gives "dereferencing pointer to incomplete type", why? I am trying to understand pointers, it's propably something about them I suppose...

Upvotes: 0

Views: 1824

Answers (5)

unwind
unwind

Reputation: 400159

If the code in main() doesn't have access to the declaration of the struct, you can't use it like you do.

Either make the declaration public (in the module.h) or make the allocation inside the module.

Also you can't allocate a string (char *) to a single char, but that's a different error message.

Also, please don't cast the return value of malloc() in C.

Upvotes: 6

dhein
dhein

Reputation: 6555

Key is of type char but "word" is a string literal what means it has type char *

Upvotes: 0

Johann Gerell
Johann Gerell

Reputation: 25601

Since this compiles pefectly:

#include <stdlib.h>

typedef struct database {
    char key;
    char value;
    struct database *next;
} Database;

int db_sizeOfStruct() {
    return sizeof(struct database);
}

int _tmain(int argc, _TCHAR* argv[])
{
    Database *database;
    database = (Database *)malloc(db_sizeOfStruct());

    database->key = 'w';//"word";

    return 0;
}

I assume you have this in a separate file that is unknown to main:

typedef struct database {
    char key;
    char value;
    struct database *next;
} Database;

int db_sizeOfStruct() {
    return sizeof(struct database);
}

Then this main have no idea what Database is:

int _tmain(int argc, _TCHAR* argv[])
{
    Database *database;
    database = (Database *)malloc(db_sizeOfStruct());

    database->key = 'w';//"word";

    return 0;
}

Also, see the assigning of "word" to a char, which obviously cannot be on purpose.

Upvotes: 1

mcleod_ideafix
mcleod_ideafix

Reputation: 11448

The problem is key, which is a char. You are trying to assign a pointer to char to a char.

Upvotes: 1

mondrasovic
mondrasovic

Reputation: 178

Your structure definition should look like:

typedef struct database {
     char *key;
     char value;
     struct database *next;
} Database;

Look at

char *key;

Your previous member was:

char key;

Just a single character that cannot hold a pointer to the "word" string.

Anyway, I have never seen using a function to return a size of some type.

malloc(sizeof(struct database));

is ugly?

Upvotes: 0

Related Questions