可以存放任意数据类型的栈实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct 
{
	void *elems; // elements
	int elemSize; // sizeof element
	int logLength; // elements count
	int allocLength; // stack storage length
} stack;


void stackNew(stack *s, int elemSize) {
	s->elemSize = elemSize;
	s->logLength = 0;
	s->allocLength = 4;
	s->elems = malloc(4 * elemSize);
}

void stackDispose(stack *s) {
	free(s->elems);
}

void stackPush(stack *s, void *elemAddr) {
	if (s->logLength == s->allocLength)
	{
		s->allocLength *= 2;
		s->elems = realloc(s->elems, s->allocLength * s->elemSize);
	}
	void *target = (char *)s->elems + s->logLength * s->elemSize;
	memcpy(target, elemAddr, s->elemSize);
	s->logLength++;
}

void stackPop(stack *s, void *elemAddr) {
	if (s->logLength > 0)
	{
		s->logLength--;
		void * source = (char *)s->elems + s->logLength * s->elemSize;
		memcpy(elemAddr, source, s->elemSize);
	}
}


int main(int argc, char const *argv[])
{
	stack s;
	int i = 10;
	stackNew(&s, sizeof(int));
	stackPush(&s, &i);
	stackPush(&s, &i);
	int j = 0;
	stackPop(&s, &j);
	printf("%d\n", j); // should print 10
	stackDispose(&s);
	return 0;
}