Reputation: 375
Hi I have a problem I'm trying to initialize an hashtable with an array that contains list but when I'm using a for loop, all the data are "shared". I've to initialize mannualy like that :
struct objec_listt A,B; // Initialization of 2 two structure A and B
INIT_LIST_HEAD(&A.list); // A is headlist
INIT_LIST_HEAD(&B.list); // B is headlist
hashtable->tab[0]= &A; // I insert A into the array
hashtable->tab[1]= &B; // I insert B into the array
insert(1,tab[0]); // insert 1, not real syntax
insert(2,tab[0]); // insert 2
insert(3,tab[1]); // insert 3
Now I print tab[0] and tab[1] with my own function and I get
tab[0] = 1,2
tab[2]= 3
Ok it works as I want
If I do like that It doesnt work :
for(i=0; i<2; i++)
{
struct objec_listt A;
INIT_LIST_HEAD(&A.list);
hashtable->tab[i] = &A
}
insert(1,tab[0]); // insert 1,
insert(2,tab[0]); // insert 2
insert(3,tab[1]); // insert 3
If I do a printf :
tab[0] : 1,2,3
tab[1] : 1,2,3
So the problem is like I'm trying to create "many object" that will be head of list, and for each I need to initialize an array with a size of 100, so that why I'm looking to do with loop
Thanks !
Upvotes: 0
Views: 46
Reputation: 84579
Continuing from the comment, in other words, you would need something similar to the following to avoid the declaration within the for
loop code block:
struct objec_listt A[2];
for(i=0; i<2; i++)
{
INIT_LIST_HEAD(&A[i].list);
hashtable->tab[i] = &A[i];
}
insert(1,tab[0]); // insert 1,
insert(2,tab[0]); // insert 2
insert(3,tab[1]); // insert 3
In your example, when you declare struct objec_listt A
within the for loop block, A
has a lifetime only within the block between the {}
. When the for loop exits, the memory of A
is marked as released and can then be use again by your program for anything it needs -- that's not what you want. By moving the declaration outside of the for loop, you insure that A
continues to exist in scope until you exit the block that contains A
.
Upvotes: 1