Hello!
I wanted to write a standard stack in C but I am not sure if my stk_size() function could work on other platforms except for my 32bit pc. I read that its not good to cast a pointer to int. But what could be a better implementation? I dont want to add a "size"-variable because its redundant in my eyes.
Here are some parts of the source:
#define MAX_STACK_SIZE 100
typedef struct stk stack;
struct stk
{
/* Stack */
int * stk;
/* Pointer to first free element of stack */
int * sp;
};
void stk_init(stack* s)
{
/* Allocate memory for stack */
s->stk = malloc(sizeof(s->stk) * MAX_STACK_SIZE);
/* Set stack pointer to first free element of stack -> 0 */
s->sp = s->stk;
}
int stk_size(stack* s)
{
return ((int) s->sp - (int) s->stk) / sizeof(int *);
}
int main(int argc, char * argv[])
{
stack * s;
stk_init(s);
}
Thank you!