- class CStack
- {
- public:
- CStack(void);
- ~CStack(void);
- int Push(const void* lpSrc, int nSize);
- int Pop(void* lpDest);
- private:
- int head;
- char buf[100];
- };
- /********************************************************************************
- 函数名称:
- 功能描述:
- 入口参数:
- 出口参数:
- 返 回 值:
- ********************************************************************************/
- CStack::CStack(void)
- {
- head = 0;
- //memset(buf,0,sizeof(buf));
- for (int i=0; i<sizeof(buf); i++)
- {
- buf[i] = 0;
- }
- }
- /********************************************************************************
- 函数名称:
- 功能描述:
- 入口参数:
- 出口参数:
- 返 回 值:
- ********************************************************************************/
- CStack::~CStack(void)
- {
- }
- /********************************************************************************
- 函数名称:int CStack::Push(const void* lpSrc, int nSize)
- 功能描述:入栈操作,将@lpSrc指向的@nSize个字节的数据存入堆栈
- 入口参数:@lpSrc - 入栈数据的首地址,@nSize - 入栈数据的大小(以字节为单位)
- 出口参数:
- 返 回 值:0 - 入栈成功,!0 - 入栈失败
- 典型应用:int a = 10; CStack::Push(&a, sizeof(a));
- ********************************************************************************/
- int CStack::Push(const void* lpSrc, int nSize)
- {
- if ((head + nSize) >= sizeof(buf))
- {
- return 0x01; //栈溢出
- }
- if (nSize > 255)
- {
- return 0x02; //一次压栈空间过大
- }
- for (int i=0; i<nSize; i++)
- {
- buf[head] = ((const char*)lpSrc)[i];
- head++;
- }
- buf[head] = nSize;
- head++;
- return 0;
- }
- /********************************************************************************
- 函数名称:int CStack::Pop(void* lpDest = NULL)
- 功能描述:弹栈操作,将最后一次入栈的数据弹出
- 入口参数:
- 出口参数:@lpDest - 用来接收弹出的数据,如为 NULL,则弹出的数据将丢失
- 返 回 值:0 - 弹栈成功,!0 - 弹栈失败
- ********************************************************************************/
- int CStack::Pop(void* lpDest = NULL)
- {
- if (head < 2)
- {
- return 0x01; //栈空,不可再弹栈
- }
- //head--;
- int pop_size = buf[head-1];
- if (head < pop_size)
- {
- return 0x02; //弹出的数据大小与压入时不匹配
- }
- head--;
- buf[head] = 0x00;
- for (int i=0; i<pop_size; i++)
- {
- head--;
- if (NULL != lpDest)
- {
- ((char*)lpDest)[pop_size - i - 1] = buf[head];
- }
- buf[head] = 0x00;
- }
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/220120131838.html
来源: http://www.codesnippet.cn/detail/220120131838.html