0

I have a function call addNode that should add a new node, but when I try it doesn't add any of them, it prints nothing, I've been trying for a few hours and I'm stuck on this.

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int value;
    struct node *next;
};

typedef struct node Node;
typedef struct node *NodePtr;

NodePtr AddNode(NodePtr listStart, int value){
    NodePtr newNode = malloc(sizeof(Node));  

    newNode->value = value;
    newNode->next = listStart;
    listStart = newNode;

}

void printList(NodePtr list){
    NodePtr handledList;
    while (handledList !=NULL)
    {
        printf("%d --> ", handledList->value);
        handledList=handledList->next;
    }
    
}

int main(){
    NodePtr list;

    AddNode(list, 5);
    AddNode(list, 25);
    AddNode(list, 15);

    printList(list);
}
camteh
  • 1
  • 1
  • Arguments in C are *copies* of what are passed, so modifying them in callee function won't affect what is passed in caller. You should pass pointers to what should be modified to have callee modify what is specified from caller. – MikeCAT Jun 24 '21 at 02:17
  • Remember that arguments are passed *by value*, which means the value is *copied* into the argument variable. Modifying this variable will only modify the local copy, not the original. Either emulate pass by reference or return the new value. – Some programmer dude Jun 24 '21 at 02:19
  • @MikeCAT I thought I was, sorry ive been doing taking C classes for the past few weeks, i thought "typedef struct node *NodePtr;" was making NodePtr a pointer type. im just confused, i looked up answers for other similar questions and they all say the same, im just having issues since i already thought im using them – camteh Jun 24 '21 at 02:40
  • You want the function to modify `list`, so you have to pass a pointer to `list`. It is not important for this rule whether what to modify is a pointer or not. – MikeCAT Jun 24 '21 at 03:07

0 Answers0