I have the following code:
typedef struct element{
int value;
int numberOfValues;
struct element * next;
} Element;
static int setnum = 0; // this is a key that identifies the set
int s, i; // s is input by the user to identify a set | i is a loop counter
Element * prev, * curr;
Element * larray[MAXSETS];
And then, a function that allows the user to create a set of elements:
int create(void)
{
if (setnum > MAXSETS)
printf("Error. Maximum value of sets reached.\n");
else
{
setnum++;
larray[setnum] = (Element *) malloc(sizeof(Element));
larray[setnum]->next = NULL;
larray[setnum]->numberOfValues = 0;
// larray[setnum] practically becomes the head
}
return setnum;
}
And an add function:
void add(int s, int x)
{
static Element * hold = NULL;
printf("Hello!\n");
if (larray[s]->numberOfValues >= MAXELEMENTS) // the set must be finite
{
printf("Error. Set is full.\n");
}
else
if (larray[s]->numberOfValues == 0)
{
larray[s]->value = x;
larray[s]->numberOfValues++;
hold = larray[s];
}
else
{
prev = (Element *) malloc(sizeof(Element));
prev = hold;
prev->next = hold;
hold->next = NULL;
hold->value = x;
printf("Done!\n");
larray[s]->numberOfValues++;
}
printf("Bye!\n");
}
And finally, a display function:
void display(int s)
{
curr = larray[s];
for (i = 0; larray[s]->numberOfValues; i++)
{
printf("%d\n", larray[s]->value);
larray[s] = larray[s]->next;
}
}
However, when I pass these functions in a drive, only 1 number is displayed. Either the display function is wrong, or the add function is wrong, but I can't seem to get the problem? Any ideas?
Thanks.
prev = malloc(...)followed byprev = holdis very sospiciousholdis declared asstaticin the function? are you sure you want it that way?? it will not initialized for every function call?