Sunday, 8 September 2013

Why doesn't the following code work?

Why doesn't the following code work?

The following code attempts to create a new variable of type presence( a
kind of structure) but when I run it through gdb, it shows that the
variable has the same address in every iteration? Shouldn't a local
variable get a different address when it is being redeclared?
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++;
}
When a item of type presence is put inside the hashtable, should I
allocate the memory and then assign item or do it simply(refer the
following code)
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;
}

No comments:

Post a Comment