Search code examples
cpointerspointer-to-pointer

Pointer-to-pointer not working during function call?


I am trying to write a separate file with helper functions for stack operations. I want to pass the stack top by reference as an argument to stack operations from the main file.

Since top is getting modified, I am passing the pointer top by reference. But even then, it is not working. Where am I going wrong?

P.S.: I know that this is not the best way to implement Stack, but i just wanted to understand why it is not working.

//Stack.h

void print(stacknode **P)
{

    stacknode *S;
    S=*P;

    printf("Printing stack from top to bottom...\n");
    stacknode *temp=S;
    while(temp != NULL)
    {
        printf("%d\t", temp->data);
        temp=temp->next;
    }
    printf("\n");
}


void push(stacknode **P, int n)

{

    stacknode *S;
    S=*P;
    stacknode *new=(stacknode *)malloc(sizeof(stacknode));
    new->data=n;
    new->next=S; 
    S=new;
    print(&S);

}

//main.c

main()
{
    printf("Creating new stack...\n");
    stacknode *S=NULL;

    printf("Pushing first number....\n");
    push(&S, 2);

    print(&S);/*Prints nothing*/

}

Solution

  • Since top is getting modified, I am passing the pointer top by reference.

    But you don't use that fact to change the top. Here's one solution (I haven't compiled or tested this so it may contain errors):

    Stack.h: (declarations only in header files, no code)

    typedef struct stacknode stacknode;
    struct stacknode {
        stacknode* next;
        int data;
    };
    
    void print(stacknode* top); // no need for ptr ref
    void push(stacknode** ptop);
    

    Stack.c:

    #include "Stack.h"
    #include <stdio.h>
    
    void print(stacknode* top)
    {
        printf("Printing stack from top to bottom...\n");
        for (stacknode* p = top; p; p = p->next)
        {
            printf("%d\t", p->data);
        }
        printf("\n");
    }
    
    void push(stacknode** ptop, int n)
    {
        stacknode* p = malloc(sizeof *p); // don't cast malloc in C
        if (!p)
            /* handle out of memory */;
        p->data = n;
        p->next = *ptop; 
        *ptop = p;
        print(p);
    }
    

    main.c:

    #include "Stack.h"
    #include <stdio.h>
    
    int main(void) // declare return type
    {
        printf("Creating new stack...\n");
        stacknode* S = NULL;
    
        printf("Pushing first number....\n");
        push(&S, 2);
    
        print(S);
        return 0;
    }