#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct
{
void *elems;
int elemsize;
int loglength;
int alloclength;
} stack;
void StackNew(stack *s, int elemSize)
{
assert(elemSize>0);
s->elemsize = elemSize;
s->loglength=0;
s->alloclength=4;
s->elems = malloc(s->alloclength*elemSize);
assert(s->elems != NULL );
}
void StackFree(stack *s)
{
free(s->elems);
}
static void StackGrw(stack *s)
{
s->alloclength *= 2;
s->elems = realloc(s->elems, s->alloclength * s->elemsize);
}
void StackPush(stack *s, void *elemAddr)
{
if(s->loglength == s->alloclength )
{
StackGrw(s);
}
void *p=(char*)s->elems + s->loglength * s->elemsize;
memcpy(p, elemAddr, s->elemsize);
s->loglength++;
}
void StackPop(stack *s, void *eleAddr)
{
void *source = (char *)s->elems + (s->loglength -1 ) * s->elemsize ;
memcpy(eleAddr, source, s->elemsize);
s->loglength--;
}
int main()
{
double d = 0.00;
double d1 = 3.1415;
double d2 = 99.99;
stack S;
StackNew(&S, sizeof(double));
StackPush(&S, &d1);
StackPush(&S, &d2);
StackPop(&S, &d);
printf("%f\n", d);
StackPop(&S, &d);
printf("%f\n", d);
StackFree(&S);
printf("Hello world!\n");
return 0;
}
C语言小函数
最新推荐文章于 2022-02-23 15:02:25 发布