Reputation: 752
I am looking to implement a stack in a C program with which I was thinking about using an unsigned char * as a base. This would be the bottom of the stack and all other registers and information would be a displacement of this address. However, I cannot seem to understand how to do this properly. I was thinking of doing something like this...
//Info: Store 20 at address x0000007c
unsigned char * base = 0;
int address = x0000007c;
(base + address) = 20;
The C compiler does not like this so I was wondering how to fix this or do something similar without losing my pointer.
Upvotes: 0
Views: 789
Reputation: 16406
The compiler doesn't like your code because it's conceptually wrong; base + address is not an lvalue, and even if it were it has the wrong type: you can't store an int into a char*. But this is logically correct:
base[address] = 20;
or, equivalently,
*(base + address) = 20;
although it isn't functionally correct because base doesn't point to valid memory. You need to allocate your stack, either as a static array or via malloc, and assign it to base, e.g.,
unsigned char* base = malloc(STACKSIZE);
if (!base) out_of_memory();
Upvotes: 3
Reputation: 19504
For a stack, the easiest is probably to use two pointers,
enum { STACKSZ = 100 };
char *base = malloc(STACKSZ);
char *top = base;
Then you can push with
*top++ = 'H';
and pop with
char x = *--top;
and get size with
int sz = top-base;
Note this code doesn't check for stack over-/under-flow.
Upvotes: 0