Struct and Pointers
So in my code I have two structures. The first is a node which contains an
int value and a pointer to another node. The second structure is used to
create an array of 10 pointers each point to a another node. And it also
contains link2 which will be used to traverse the array and all the nodes
that it points to. I'm trying to add 3 nodes each holds the value 3 into
the third index of the array. The pointer in the third index should point
to the first 3 then that should point to the second three and so on. When
I put add(a,3) three times and then print it it only prints out two nodes
rather than three. I tried tracing the code but that still didn't make any
sense to me because I always end up with three nodes. Can someone point me
in some direction? Thanks!:)/>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
int x;
struct node *link;
};
struct listofnodes{
struct node *alist[10];
struct node *link2;
};
addFirst(struct listofnodes *a,int num)
{
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
a->alist[num]=nodeone;
//printf("IT WENT THROUGH\n");
}
add(struct listofnodes *a,int num)
{
struct node *current;
current=a->alist[3];
struct node *nodeone = (struct node *)malloc(sizeof(struct node));
nodeone->x=num;
current->x=5;
{
while(a->alist[3]!=NULL)
{
if(a->alist[3]->link==NULL)
{
a->alist[3]->link=nodeone;
printf("IT WENT THROUGH\n");
break;
}
a->alist[3]=a->alist[3]->link;
}
}
}
main(void)
{
struct listofnodes *a=(struct listofnodes *)malloc(sizeof(struct
listofnodes));
//a->alist[3]=NULL;
addFirst(a,3);
add(a,3);
add(a,3);
add(a,5);
}
No comments:
Post a Comment