Login Register






Tutorial [C] Type Ambiguous Stack filter_list
Author
Message
RE: [C] Type Ambiguous Stack #2
You could also use macro's to easily create a defined stack type:
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.

Reply





Messages In This Thread
[C] Type Ambiguous Stack - by phyrrus9 - 12-31-2014, 09:05 AM
RE: [C] Type Ambiguous Stack - by 0xDEAD10CC - 01-01-2015, 11:35 PM
RE: [C] Type Ambiguous Stack - by phyrrus9 - 01-02-2015, 10:05 PM
RE: [C] Type Ambiguous Stack - by 0xDEAD10CC - 01-03-2015, 05:37 PM
RE: [C] Type Ambiguous Stack - by phyrrus9 - 01-03-2015, 05:48 PM
RE: [C] Type Ambiguous Stack - by 0xDEAD10CC - 01-03-2015, 06:26 PM
RE: [C] Type Ambiguous Stack - by phyrrus9 - 01-03-2015, 06:28 PM
RE: [C] Type Ambiguous Stack - by 0xDEAD10CC - 01-03-2015, 06:34 PM
RE: [C] Type Ambiguous Stack - by phyrrus9 - 01-03-2015, 06:35 PM
RE: [C] Type Ambiguous Stack - by 0xDEAD10CC - 01-03-2015, 07:06 PM
RE: [C] Type Ambiguous Stack - by phyrrus9 - 01-03-2015, 07:07 PM