RE: [C] Type Ambiguous Stack 01-01-2015, 11:35 PM
#2
You could also use macro's to easily create a defined stack type:
It's just code however, so you're left to do all of the memory bounds checking on your own.
edit: What the heck is this? :S
These macros are the equivalent of a redundant statement ';' followed by a scope which calls the defined functions and mathematical operations.. The semi-colon there is useless and silly. Would you ever write code like this?
0.o
edit2: The other thing you can do is have a stack type pre-generated for you of a defined type through a few macros. Then you can generate whatever stack types you want, with the types you intend on using for the stack data.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define stack_t(T) T *
#define stack_init(T, len) malloc(len * sizeof(T))
#define stack_push(T, p, src) (memcpy(*p, src, sizeof(T)), ++(*p))
#define stack_pop(T, p) --(*p)
#define stack_free(p) free(p);
int main(void)
{
int stack_size = 5;
stack_t(int) stack_ptr = stack_init(int, stack_size);
stack_t(int) p = stack_ptr;
for (int n = 0; n < stack_size; ++n)
{
printf("push: %d\n", n);
stack_push(int, &p, &n);
}
for (int n = 0; n < stack_size; ++n)
printf("pop: %d\n", *stack_pop(int, &p));
stack_free(stack_ptr);
}It's just code however, so you're left to do all of the memory bounds checking on your own.
edit: What the heck is this? :S
Code:
#define Stack_push(obj, data, size); { memcpy(obj, data, size); obj += size; }
#define Stack_pop(obj, data, size); { obj -= size; memcpy(data, obj, size); }These macros are the equivalent of a redundant statement ';' followed by a scope which calls the defined functions and mathematical operations.. The semi-colon there is useless and silly. Would you ever write code like this?
Code:
int main(void)
{
;
{
int x = 10;
}
}0.o
edit2: The other thing you can do is have a stack type pre-generated for you of a defined type through a few macros. Then you can generate whatever stack types you want, with the types you intend on using for the stack data.




![[+]](https://sinister.li/images/modern/collapse_collapsed.png)