0

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.

4

2 に答える 2

3

概念的に間違っているため、コンパイラはコードを気に入りません。base + address は左辺値ではなく、たとえそれが間違った型であっても、int を char* に格納することはできません。しかし、これは論理的に正しいです:

 base[address] = 20;

または同等に、

 *(base + address) = 20;

base が有効なメモリを指していないため、機能的には正しくありません。静的配列として、または malloc を介してスタックを割り当て、それを base に割り当てる必要があります。

 unsigned char* base = malloc(STACKSIZE);
 if (!base) out_of_memory();
于 2013-04-24T04:20:21.177 に答える
0

スタックの場合、おそらく最も簡単なのは 2 つのポインターを使用することです。

enum { STACKSZ = 100 };
char *base = malloc(STACKSZ);
char *top = base;

次に、で押すことができます

*top++ = 'H';

とポップ

char x = *--top;

でサイズを取得します

int sz = top-base;

このコードは、スタックのオーバーフロー/アンダーフローをチェックしないことに注意してください。

于 2013-04-24T04:26:30.730 に答える