Reputation: 37
I got stuck doing stack in C. I would be grateful if anyone could help me. Here is my code:
header
typedef struct stackEl stackEl;
typedef struct Task Task;
struct stackEl{
struct Task *zad;
struct stackEl *last;
};
struct Task{
int x;
int y;
};
source
void add(stackEl *main, Task *adding)
{
stackEl tmp;
tmp.last= main;
tmp.zad = adding;
*main=tmp;
}
This one create infinite numbers of elements by pointing each other one by one instead of adding single element to stack. I don't know how to repair it. I have tried to do it like this:
void add(stackEl *main, Task *adding )
{
stackEl *tmp;
tmp = (stackEl*)malloc(sizeof(stackEl));
tmp->last= main;
tmp->zad = adding;
main=tmp;
}
Using this method element is added on the top of stack but it don't modify stack in main function.
Upvotes: 0
Views: 67
Reputation: 70929
Second version is closer to the truth. You need to allocate memory for each element you add to the stack like you do. Still note in the second version you only modify the local copy of a pointer instead of actually changing this pointer. You should pass a pointer to pointer (i.e. StackE1**
) and then do *main = tmp
.
Upvotes: 1