今天有个人问我用c语言如何写栈,使他既能保存int类型的数据,又能保存float类型的数据。 c没有模板,所以我的第一反应是:用宏。 代码如下: stack.h #include <malloc.h> #define USE_STACK(type)/ typedef struct/ {/ int len;/ int size;/ type *array;/ } STACK##type; #define DEFINE_STACK(type, name, length)/ STACK##type name;/ name.array = (type*)malloc(sizeof(type) * length);/ name.size = 0;/ name.len = length; #define STACK_PUSH(stack, value)/ if (stack.size < stack.len)/ stack.array[stack.size++] = value;/ else printf("stack is full, push failed!"); #define STACK_POP(stack, value)/ if (stack.size > 0)/ value = stack.array[--stack.size];/ else printf("stack is empty, pop failed!");/ main.cpp #include <stdio.h> #include "stack.h" USE_STACK(int); USE_STACK(float); int main() { //test stack int DEFINE_STACK(int, s, 10); STACK_PUSH(s, 10); STACK_PUSH(s, 2); int a, b; STACK_POP(s, a); STACK_POP(s, b); printf("a = %d, b = %d/n", a, b); //test stack float DEFINE_STACK(float, s1, 10); STACK_PUSH(s1, 10.1); STACK_PUSH(s1, 2.1); float c, d; STACK_POP(s1, c); STACK_POP(s1, d); printf("c = %f, d = %f/n", c, d); return 0; }