Home > database >  I'm trying to index an array of nodes (linked lists)
I'm trying to index an array of nodes (linked lists)

Time:07-18

Node struct implementation:

typedef struct node{
    int data;
    struct node* next;
} node;
typedef node* nodePtr;

Appending to my node:

// Append to node
void addTo(nodePtr* aNode, int val){
    //Create a new node to hold the value
   nodePtr temp = (nodePtr) malloc(sizeof(node));
   temp->data = val;
   temp->next = NULL;
   if(!(*aNode)){
       *aNode = temp;
       return;
   }
   nodePtr curr = *aNode;
   while(curr->next){
       curr = curr->next;
   }
   curr->next = temp;
}

Displaying my node:

void display(nodePtr aNode){
    nodePtr curr = aNode;
    while(curr){
        printf("%d \n", curr->data);
        curr = curr->next;
    }
}

So my problem here's that I'm trying to create an array of nodes and insert values into each node, while indexing said array. But I'm not getting it to work.

Here's the main stub for what I'm trying to do:

int main(){
    nodePtr* myArr = (nodePtr*) malloc(3*sizeof(nodePtr));
    int i = 0, j = 0;
    while(i < 3){
        while((j%3)!=0){
            addTo(&myArr[i], j);
            j  ;
        }
        i  ;
    }
    
    for(int j = 0; j < 3; j  ){
        display(myArr[j]);
    }
    return 0;
}

But when I print it, I don't get any thing. Do I need to instantiate every node in the array first before I can get it to work?

CodePudding user response:

There are two major issues with this program. The first is that you have not initialized your list pointers. You allocate storage for them, but their actual values can be anything. Attempting to dereference such values will result in Undefined Behavior.

You could memset after calling malloc, but it is recommended to use calloc for your allocation instead, which will also zero-initialize the memory (i.e. set all bytes to zero, which is equivalent to all the pointers being NULL):

nodePtr* myArr = calloc(3, sizeof(nodePtr));

The second issue is you never push anything onto the lists. The reason is that j is initially zero and so your while-loop is never entered (the condition (j%3)!=0 is false).

You could have detected this by stepping through your program with a debugger attached, or selectively adding printf statements to inspect which parts of your program execute. For example, adding printf("addTo() called\n"); at the top of the addTo function would have immediately alerted you to the fact it is never called.

One way to fix it is with a do-while instead:

do {
    addTo(&myArr[i], j);
    j  ;
} while((j % 3) != 0);

With this type of loop, the body is always executed before testing the loop condition. That allows j to be modified in the loop before being checked.

By applying these fixes for the two issues I've identified, your program operates the way you intended.

  • Related