Antonio
Antonio

Reputation: 75

Error on add element of struct into array of the same struct

Hello I am triyng to add a struct called hash_entry to an array of hash_entry inside of another struct(hash_table), but I am receive this error:

hash.c:67:5: error: invalid use of undefined type ‘struct hash_entry’
 my_table->table[0] =  e;
 ^
hash.c:67:30: error: dereferencing pointer to incomplete type
 my_table->table[0] =  e;

My structs:

typedef struct hash_entry{
  int value;
} Hash_entry;

typedef struct hash_table{
  struct hash_entry * table; 

} Hash_table;

My code to alloc the memory to the array and to add:

Hash_entry e;
e.value =  10;

Hash_table *my_table = (Hash_table *) malloc(sizeof (Hash_table));

my_table->table = malloc (sizeof (Hash_entry) * 10);

my_table->table[0] =  e;

Upvotes: 0

Views: 36

Answers (1)

gsamaras
gsamaras

Reputation: 73444

You give your variable the same name with the type, change this to that:

hash_table *my_hash_table = (hash_table*) malloc(sizeof (hash_table));

my_hash_table->table = malloc (sizeof (hash_entry) * 10);
my_hash_table->table = NULL;

my_hash_table->table[0] =  e;

and then notice that this:

my_hash_table->table = NULL;

actually is wrong, since you want to use table, so remove it.


Putting all together (and personally checking mystruct.c):

#include <stdio.h>
#include <stdlib.h>

typedef struct hash_entry{
        int value;
} hash_entry;

typedef struct hash_table{
        struct hash_entry * table; 
} hash_table;

int main(void) {
        hash_entry e;
        e.value =  10;

        hash_table *my_hash_table = (hash_table*) malloc(sizeof (hash_table));
        my_hash_table->table = malloc (sizeof (hash_entry) * 10);

        my_hash_table->table[0] =  e;
        printf("Value = %d\n", my_hash_table->table[0].value);
        return 0;
}

Output:

gsamaras@gsamaras:~$ gcc -Wall px.c 
gsamaras@gsamaras:~$ ./a.out 
Value = 10

Upvotes: 2

Related Questions