您的位置:首页 > 编程语言 > C语言/C++

C语言:泛型栈的一次尝试

2012-04-19 16:09 148 查看
尝试了用C做一个泛型的栈,抛出来跟大家交流一下。

#include <stdio.h>
/**
* 	Make a struct for stacks.
*	I hope to make a generic struct of stacks.
*	I may have a try.
*
*/

/** Two variables:
*		01.	pointer to char.
*		02. the position of the stack.
*				from 0 to MAX
*		03. the length of the array of char which is malloc.;
*/

typedef struct Stack *StackSP;

struct Stack
{
void *pt;
size_t top;
size_t length;
};

/**	function judge whether stack is empty.
*	argument sp is a pointer to Stack.
*
*	should be aware that top is equal to zero while stack is empty.
*/
#define size_t ifempty(StackSP sp)  sp->top

/**	Push an element into the top of the stack.
*/
#define push(vartype, stacksp, value)\
if(stacksp->top == stacksp->length) fprintf(stderr,"error : stack is full.");\
((vartype *)stacksp->pt)[stacksp->top++] = value ;

/**	Pop()function return  an element from the top of the stack.
*		Warning : the element is also an pointer to void.
* 			so you cannot referrence the variable by this pointer,
* 			you show make some conventions.
*/
#define pop(vartype, stacksp)\
(stacksp->top == 0) ? NULL : (((vartype *) stacksp->pt)[--stacksp->top])

/**	Free the space applied.
*/
#define closestack(vartype, stacksp) if(stacksp->pt == NULL){\
free((vartype *)stacksp->pt);\
stacksp->top = 0;}

/**	Malloc a space for stack.
*
**/

#define openstack(vartype,stacksp,op_length)  \
stacksp->pt = malloc(sizeof(vartype) * op_length );\
stacksp->length  = op_length; \
stacksp->top = 0;


编译时爆出几个warning,显然用C做泛型还是有些不理智。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: