Implementación de pila sin usar punteros

I need to implement a very basic stack data structure for keeping integers in C without using pointers. Is this possible using only arrays? Simple pseudo code would be highly appreciated.

Edit: I'm using a model checking tool called UPPAAL that supports the basic functionalities of C and I need to use a recursive function which UPPAAL doesn't support. I thought about implementing the recursion using my own stack because UPPAAL doesn't support pointers. Any better ideas?

preguntado el 28 de julio de 12 a las 19:07

Are you allowed to needlessly waste stack memory? -

Why are you allowed to use arrays but not pointers? They are fundamentally the same thing. -

Is the restriction against pointers a restriction of the assignment or because you are unsure about using them yourself? -

Smells like homework to me. I can't imagine another scenario which would disallow the use of pointers. -

Then why do you have a "no pointer" requirement? That doesn't seem... sane... in the context of non-academic code. -

1 Respuestas

Assuming that you're allowed to make one dynamic allocation for the entire structure (which you must, one way or another), you can just use enteros for an offset:

unsigned int capacity = 100;
unsigned int top      = 0;

int * buf = malloc(sizeof(int) * capacity);

// push:
buf[top++] = n;

// pop:
int value = buf[--top];

// empty:
int is_empty = (top == 0);

// increase capacity:
if (top == capacity)
{
    int * tmp = realloc(buf, capacity * 2 * sizeof(int));
    if (!tmp) { /* out of memory, die */ }
    buf = tmp;
    capacity *= 2;
}

// destroy
free(buf);

This code is just for exposition; in your implementation you would obviously check for overflow and underflow.

Respondido 03 ago 12, 22:08

push execute buf[top++]=n, after pop execute value=buf[top--] value is not n, value is undefined! - AZULPIXY

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.