Created
January 27, 2021 16:04
-
-
Save PurityLake/d2843c6151d221d7944bbf573d1a91c9 to your computer and use it in GitHub Desktop.
Generic Stack in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include "stack.h" | |
typedef struct stack(int) IntStack; | |
int main(int argc, char *argv[]) { | |
createStack(IntStack, stack, int, 5); | |
pushStack(stack, 10); | |
pushStack(stack, 20); | |
int out; | |
popStack(stack, out, -1); | |
printf("%d\n", out); | |
popStack(stack, out, -1); | |
printf("%d\n", out); | |
freeStack(stack); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stddef.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#define stack(type) \ | |
{ \ | |
size_t capacity; \ | |
size_t len; \ | |
type *objects; \ | |
} | |
#define createStack(StackType, name, ObjType, cap) \ | |
StackType *name; \ | |
name = malloc(sizeof(StackType)); \ | |
name->capacity = cap; \ | |
name->len = 0; \ | |
name->objects = malloc(sizeof(ObjType) * cap) | |
#define pushStack(s, obj) \ | |
do { \ | |
if (s->len + 1 >= s->capacity) { \ | |
s->capacity *= 2; \ | |
s->objects = realloc(s->objects, sizeof(obj) * s->capacity); \ | |
} \ | |
s->objects[s->len] = obj; \ | |
s->len++; \ | |
} while(0) | |
#define popStack(s, varname, defaultValue) \ | |
do { \ | |
if (s->len - 1 >= 0) { \ | |
s->len--; \ | |
varname = s->objects[s->len]; \ | |
} else { \ | |
varname = defaultValue; \ | |
} \ | |
} while(0) | |
#define freeStack(s) \ | |
free(s->objects); \ | |
free(s); \ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment