David Tao David Tao - 1 month ago 5
C Question

Pointer passed in to function not reassigning

So I'm trying to implement a linked list stack that takes in char arguments and adds them to the link list with it's ascii code as the value of the nodes.

I pass in my nstack pointer into my push function and re-assign it to new_node in order to create a new top, but my push function doesn't seem to be reassigning my nstack node - it just prints the originally initialized nstack value. Why isn't nstack being reassigned?

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

struct list_node {
int element;
struct list_node * pnext;
};

void push(struct list_node *operators, int e);

int pop(struct list_node *operators);


int main(int argc, char *argv[]) {
int newvalue = (int)argv[1][0];
struct list_node * nstack = (struct list_node*)malloc(sizeof(struct list_node));

nstack->element = newvalue;
nstack->pnext = NULL;
int i;
for (i = 2; i < argc; i++) {
push(nstack, (int)argv[i][0]);
}
printf("top: %d\n", nstack->element);
}

void push(struct list_node *nstack, int e) {
struct list_node * new_node = (struct list_node*)malloc(sizeof(struct list_node));
new_node->pnext = nstack;
new_node->element = e;
nstack = new_node;
}

Answer

Because you are passing a copy of pointer (by value). You need something like this (pointer to pointer):

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

struct list_node {
    int element;
    struct list_node * pnext;
};

void push(struct list_node **operators, int e);

int pop(struct list_node *operators);


int main(int argc, char *argv[]) {
    //int newvalue = (int)argv[1][0];
    int newvalue = 1;
    struct list_node * nstack = (struct list_node*)malloc(sizeof(struct list_node));

    nstack->element = newvalue;
    nstack->pnext = NULL;

    int i;
        for (i = 2; i < 7; i++) {
            //push(nstack, (int)argv[i][0]);
            push(&nstack, i);
        }
    printf("top: %d\n", nstack->element);
}

void push(struct list_node **nstack, int e) {
    struct list_node * new_node = (struct list_node*)malloc(sizeof(struct list_node));
    new_node->pnext = *nstack;
    new_node->element = e;
    *nstack = new_node;
}
Comments