以下代码尝试创建一个类型为present(一种结构)的新变量,但是当我通过gdb运行它时,它表明该变量在每次迭代中都具有相同的地址吗?重新声明局部变量时,是否不应该获得其他地址?

presence* hashtable[MAX];
int i = 0;

printf("---------ENTERING DATA FOR THE HASHTABLE------------------\n");
while (i < MAX)
{

        presence item; /* Same address on every iteration */
        printf("Enter item id : ");
        scanf("%d",&item.id);

        printf("Enter item name : ");
        item.name = (char*)malloc(SIZE*sizeof(char));
        getchar();
        fgets(item.name,SIZE,stdin);

        putItem(hashtable,&item);
        i++;

}

当将存在类型的项放在哈希表中时,我应该分配内存,然后分配项还是简单地执行(请参阅以下代码)

int putItem(presence* hashtable[], presence* item)
{
    int key = hash(item->id);
    hashtable[key] = (presence*)malloc(sizeof(presence)); /* Required or not? or do the below straight away?*/
    hashtable[key] = item;
}

最佳答案

对于1:您应该具有presence *item;指针类型变量,对其进行分配并使用它来填充数据。您当前的实现在每次迭代中使用相同的变量。

while (i < MAX)
{

        presence *item; /* pointer */
        item = malloc(sizeof(*item));
        printf("Enter item id : ");
        scanf("%d",&item->id);

        printf("Enter item name : ");
        item->name = (char*)malloc(SIZE*sizeof(char));
        getchar();
        fgets(item->name,SIZE,stdin);

        putItem(hashtable,item);
        i++;

}


对于2:您不需要分配内存。线

hashtable[key] = (presence*)malloc(sizeof(presence));


不需要。

但是,请确保key小于MAX,即hashtable的大小。另外,您可能需要适当地处理冲突。

关于c - 为什么以下代码不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18685734/

10-11 18:23