Reputation: 8829
I created an implementation of a Stack in C. Here are the relevant definitions/methods, I have stripped all the error checking/reallocation so don't comment on that:
typedef struct {
Element *data;
int top;
int size;
} Stack;
typedef void* Element;
void push(Stack *s, Element e) {
s->data[(s->top)++] = e;
}
Now in another method, I have a loop in which I call push()
. Something like
int character;
Stack *s = createStack();
while((character = getchar()) != EOF) {
int tmp = character;
push(s, &tmp);
}
However, this doesn't function how I want it to. The stack receives the same address everytime, thus when each character is read, the "contents" of the entire stack change. How do I modify this to do what I want. e.g when abcde
is read, the stack looks like (top-down) e,d,c,b,a
.
Upvotes: 2
Views: 171
Reputation: 55593
As an addendum to the above answer:
You can simply cast your int value to a pointer:
push(s, (int *) tmp);
Upvotes: 0
Reputation: 75160
int tmp = character;
push(s, &tmp);
There you are passing the address of the local variable tmp
to the function push
which is storing the pointer in itself. Every time the loop is iterated, the variable is destroyed and another local variable is made (most likely on top of the old variable), so you are storing pointers to destroyed variables.
If you want your stack to be generic and work with void*
, you'll have to make sure the lifetimes of the objects you store is longer than the lifetime of the stack. One way you can do this is allocate the variables on the heap:
char* c = malloc(sizeof(char)); // or malloc(1) but sizeof is there in case you
// change the type later
*c = character;
push(s, c);
Then deallocate each one after the stack is no longer in use so you don't get a memory leak.
Upvotes: 3