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

尝试了用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做泛型还是有些不理智。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值