C++编程范式栈的泛型写法 (二)

2014-11-24 00:33:28 · 作者: · 浏览: 11
*********/
/* 释放栈空间 */
/************************************************************************/
void stackDelete(stack *s){
free(s);

};

/************************************************************************/
/* chuzhan */
/************************************************************************/

/************************************************************************/
/* 将元素elem入栈 */
/************************************************************************/
//
// void stackPush(stack *s,void *add){
//
// if(s->logicallen == s->allocalength){
// s->allocalength *=2; //等价于s->allocalength = s->allocalength*2
// s->elems = (int *)realloc(s->elems,s->allocalength*sizeof(int));
// }
// assert(s->elems != NULL);
// s->elems[s->logicallen] =value;
// s->logicallen++;
// };

void stackGrow(stack *s){

s->allocalength*=2;
s->elems = realloc(s->elems,s->elemSize*s->allocalength);

}
/************************************************************************/
/* 将元素elem入栈 */
/************************************************************************/
void stackPush(stack *s,void *elemAddr){

if(s->logicallen == s->allocalength){
stackGrow(s); //需要扩容了

}
//手动计算元素地址,因为void*类型,系统比不知道该怎么处理。所以需要自己计算出入栈和出栈时元素的地址。
//从add地址下的内容拷贝到target的地址,拷贝长度为elemSize
void * target = (char *)s->elems+s->logicallen*s->elemSize;

memcpy(target,elemAddr,s->elemSize);


s->logicallen++;
};
void main(){


int i=1;
int j=2;
int m = i+j*2;
cout<



}
总结:

下面这个方法就是获得top的地址。入栈。

void * target = (char *)s->elems+s->logicallen*s->elemSize;