0

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*/

}
  • 3
    `S=*P;` makes a copy of `*P`. Assigning to `S` does not change `*P`. – chris Jul 16 '14 at 23:44
  • `S=new;print(&S);` --> `*P = new;print(P);` – BLUEPIXY Jul 16 '14 at 23:52
  • BTW: Never define non-inline functions in header files, only declare them there. Those belong in implementation files (.c). Also, [Don't cast the result of malloc (and friends)](http://stackoverflow.com/questions/605845). Third, always use full function prototypes: Don't rely on implicit `int` return type. – Deduplicator Jul 16 '14 at 23:53

1 Answers1

0

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;
}
Jim Balter
  • 16,163
  • 3
  • 43
  • 66