2016-04-06 4 views
0

Привет Я triyng добавить на структуру под названием hash_entry в массив hash_entry внутри другого структуры (hash_table), но я получаю эту ошибку:Ошибка на добавления элемента структуры в массив той же структуры

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; 

Мои: Структуры

typedef struct hash_entry{ 
    int value; 
} Hash_entry; 

typedef struct hash_table{ 
    struct hash_entry * table; 

} Hash_table; 

Мой код Alloc памяти для массива и добавить:

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; 
+0

Почему ваш тип и переменная имеет то же имя? Что вы достигнете? –

ответ

2

Дает года Ур переменной то же имя с типом, изменить это к тому, что:

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; 

и обратите внимание на то, что это:

my_hash_table->table = NULL; 

на самом деле это не так, так как вы хотите использовать table, поэтому удалить его.


Собираем все вместе (и лично проверять 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; 
} 

Выход:

[email protected]:~$ gcc -Wall px.c 
[email protected]:~$ ./a.out 
Value = 10 
+0

Хорошо, я изменил имя и удалю это, но ошибка все еще происходит ... Также я обновляю в первом комментарии. – Antonio

+0

@ Антонио, * пожалуйста * проверьте мой обновленный ответ, это лучше? :) – gsamaras

Смежные вопросы