结构未复制到其他结构

问题描述 投票:0回答:1

所以,我有这个结构:

typedef struct person {
   char *name;
   int age;
   struct person* next;
}

我也有我的hash_table:

person *table[50];

我有一个函数可以获取要使用的变量:

void add_person() {
   person *new_person = (person*) malloc(sizeof(new_person));
   char str1[50];
   int age;
   scanf(" %[^:\n]:%d",str1,&age);
   new_person->name = (char*) malloc((strlen(str1)+1)*sizeof(char));
   strcpy(new_person->name,str1);
   new_person->age =age;
   printf("%s %d",new_person->name,new_person->age) //checking if struct variables change (they do)
   insert_hash_table(new_person);
   free(new_person);
   free(new_person->name);   
 }

这是我的insert_hash_table(person * p)向我的哈希表添加一个元素:

void insert_hash_table(person *p) {
    int index = hash(p->name); //hash function
    p->next = table[index];
    table[index] = p;
    printf("%s",table[index]->name); //just to check if the struct was copied
 }

但是当我输入此输入时:

Josh:35

它没有打印出由于该命令而应该使用的“ Josh”:

printf("%s",table[index]->name)

有什么建议吗?感谢您能提供的任何帮助。

c pointers struct printf scanf
1个回答
0
投票

add_person分配person及其name,但insert_hash_table不复制数据,它仅引用它。因此,在add_person中释放数据后,将无法再访问该数据。同样,重新分配顺序不正确。必须先释放name,因为其指针存储在person中。只有这样,才能释放person

除了更改重新分配顺序之外,您还必须在insert_hash_table中进行实际复印。您可以通过分配另一个person来实现,通过取消引用两个指针以触发浅表副本(* hashtable_person = * person)来复制人员,然后使用strdup复制名称。

不过,我不确定next字段代表什么。 next表示一个单链列表,但是代码不记得最后插入的人能够创建一个。

在这种特定情况下,通过调用personinsert_hash_table的所有权传递给哈希表可能会更简单。然后您可以分配person,但不必担心释放。从哈希表中删除person可能会触发重新分配,或者-为了保持一致-在这种情况下,您可以将所有权转给调用方。

© www.soinside.com 2019 - 2024. All rights reserved.