Reputation: 9
I have problem in: Re-Using array of struct
The 1D array (Trans) is global:
struct Transaction
{
int Item;
float prob;
int support;
Transaction *next;
};
#define ItemNum 1000
Transaction *Trans[ItemNum];
Transaction *PairItems[ItemNum][ItemNum];
I initialize Trans as:
for (int a = 0; a <= ItemNum - 1; a++)
Trans[a] = NULL;
Then I fill this array with input from text file. In specific:
i = 0;
while (!inFile.eof())
{
FollowingItem = NULL;
getline(inFile, line);
std::stringstream in(line);
while (in >> a >> b)
{
NewItem = new Transaction;
NewItem->Item= a;
NewItem->prob = b;
NewItem->next = NULL;
if (Trans[i] == NULL)
Trans[i] = FollowingItem = NewItem;
else
{
FollowingItem->next = NewItem;
FollowingItem = NewItem;
}
}
i++;
}
Then, I print it:
i=0;
while (Trans[i] != NULL)
{
while (Trans[i] != NULL)
{
cout << Trans[i]->Item << " " << Trans[i]->prob<<" ";
Trans[i] = Trans[i]->next;
}
cout << "\n";
i++;
}
Until Now, everything is okay,
BUT
When I try to use Trans again, I can't, since the array become empty!!
for example, if I do this code:
for (int a = 0; a <= ItemNum - 1; a++)
for (int b = 0; b <= ItemNum - 1; b++)
{
PairItems[a][b] = new Transaction;
PairItems[a][b]->support = 0;
}
int k = 0;
while (Trans[k] != NULL)
{
int l = 0;
while (Trans[l] != NULL)
{
PairItems[k][l]->Item = Trans[k]->Item;
PairItems[k][l]->prob = Trans[k]->prob;
PairItems[k][l]->support += 1;
cout << PairItems[k][l]->Item << " " ;
Trans[k] = Trans[k]->next;
l++;
}
cout << "\n";
k++;
}
the compiler ignores this condition:
while (Trans[k] != NULL)
because Trans[k]=NULL. I don't know way!
But when I delete the printing code, Trans[k] != NULL and the compiler enter to the condition and execute the rest!!
I think the problem associated with the initializing the arrays of structure, but I couldn't find the solution
Please Help
Thanks
Upvotes: 0
Views: 103
Reputation: 218323
Your print code modify the array, in particular Trans[i] = Trans[i]->next;
Your print function may be written:
for (int i = 0; Trans[i] != NULL; ++i) {
for (const Transaction* it = Trans[i]; it != NULL; it = it->next) {
std::cout << it->Item << " " << it->prob <<" ";
}
cout << "\n";
}
BTW, you may use std::vector<std::list<Transaction> > Trans
instead of hard-coded array of handwritten list.
Upvotes: 1