Lately I've been writing code in C for a generic stack using an array of void pointers. After doing some tests everything seemed to be fine, until this last test:
while(i < 9) {
push_pila(mi_pila,(int*)&i);
i++;
}
As you can see I'm passing an i
as an argument into the push_pila
function. This is the code for the push_pila
function in the stack:
typedef struct {
void **vec;
int tope;
int16_t max_elementos;
}PILA;
int push_pila(PILA *mi_pila,void *val) {
if(pila_llena(mi_pila)) {
return -1;
}
else {
mi_pila->tope = mi_pila->tope + 1;
mi_pila->vec[mi_pila->tope] = val;
return 0;
}
}
Here is where the problem is, because my stack is an array of void*
containing the values of the address of val
. When I pass the value of i
I'm passing the address of it. The problem in this case is that all the values inside the stack will contain the same address therefore all the value in the stack will be the same, so when I pop the stack using the pop function I will return the same value which is the last value of i
, in my case 9
.
Is there any solution to this problem?. Or is just that this is not the best way to push elements in the array?