0

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?

13
  • Are you allowed to needlessly waste stack memory? Commented Jul 28, 2012 at 18:52
  • Why are you allowed to use arrays but not pointers? They are fundamentally the same thing. Commented Jul 28, 2012 at 18:53
  • 5
    Is the restriction against pointers a restriction of the assignment or because you are unsure about using them yourself? Commented Jul 28, 2012 at 18:55
  • 2
    Smells like homework to me. I can't imagine another scenario which would disallow the use of pointers. Commented Jul 28, 2012 at 19:00
  • 1
    Then why do you have a "no pointer" requirement? That doesn't seem... sane... in the context of non-academic code. Commented Jul 28, 2012 at 19:30

1 Answer 1

3

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 integers 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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.