0

Simple stack implementation in C:

struct Stack {
  char* data;
  Stack* prev;
};

void push(char* data, Stack** stack) {
  Stack* node = (Stack*)malloc(sizeof(Stack));
  node->data = data;
  node->prev = *stack;
  *stack = node;
}

int main() {
  Stack* top = NULL;
  push("1", &top);
  push("2", &top);
  push("3", &top);
}

then top->prev->prev->data results into 3 same as top->prev->data and top->data.

Can anybody explain why?

kassie
  • 727
  • 4
  • 11
  • 24
  • [Please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). – unwind Mar 04 '14 at 14:26
  • 1
    @unwind: It's likely that kassie is using a c++ compiler to compile this code. Otherwise there would be a number of other errors. – Bill Lynch Mar 04 '14 at 15:44
  • you have passed to `push` the buffer(pointer) of probably identical. I think that it is necessary to copy the contents by securing a new area. – BLUEPIXY Mar 04 '14 at 23:59

1 Answers1

5

So, it appears to work correctly.

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

struct Stack {
    char* data;
    struct Stack* prev;
};

void push(char *data, struct Stack** stack) {
    struct Stack* node = malloc(sizeof(struct Stack));
    node->data = data;
    node->prev = *stack;
    *stack = node;
}

int main() {
    struct Stack* top = NULL;
    push("1", &top);
    push("2", &top);
    push("3", &top);

    printf("top->data: %s\n", top->data);
    printf("top->prev->data: %s\n", top->prev->data);
    printf("top->prev->prev->data: %s\n", top->prev->prev->data);
}

The output is:

top->data: 3
top->prev->data: 2
top->prev->prev->data: 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Yes, be sure to always call your new `struct`-type with this keyword before it. You can avoid that by doing a `typedef struct MY_STRUCT { ... } MY_STRUCT;` – Stefan Marinov Mar 04 '14 at 13:07