【问题标题】:Error on add element of struct into array of the same struct将结构的元素添加到同一结构的数组中时出错
【发布时间】:2016-04-06 20:57:02
【问题描述】:

您好,我正在尝试将名为 hash_entry 的结构添加到另一个结构 (hash_table) 内的 hash_entry 数组中,但我收到此错误:

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;

我的代码将内存分配给数组并添加:

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;

【问题讨论】:

  • 为什么你的类型和变量有相同的名字?你会取得什么成就?

标签: c arrays pointers struct malloc


【解决方案1】:

你给你的变量命名与类型相同,把它改成那个:

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;
}

输出:

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

【讨论】:

  • 好的,我更改了名称并删除了它,但错误仍在发生......我也在第一条评论中更新。
  • @Antonio,检查我更新的答案,这样更好吗? :)
猜你喜欢
  • 2016-07-31
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 2015-09-02
  • 2016-06-19
  • 1970-01-01
相关资源
最近更新 更多