//2.2一个小型的C库的头文件
typedef struct STATSHtag {
int size;
int quantity;
int next;
unsigned char* storage;
}Stash;
//注意,这些函数声明用的是标准的C风格函数声明
void initialize( Stash* S , int Size );
void cleanup( Stash* S );
int add( Stash* S , void* element );
void* fecth( Stash* S , int index );
int count( Stash* S );
void inflate( Stash* S , int increase );
//2.2一个小型C库的具体实现
#include "stdafx.h"
#include "lib.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>//memcpy()
#include <stdio.h>
void initialize( Stash* S , int Size ) {
S->size = Size;
S->quantity = 0;
S->storage = 0;
S->next = 0;
}
void cleanup( Stash* S) {
if ( S->storage ) {
puts( "freeing storage" );
free(S->storage);
}
}
int add( Stash* S , void* element ) {
if ( S->next >= S->quantity )
inflate(S , 100);
memcpy(&( S->storage[S->next * S->size]) , element , S->size);//第一个参数为目标地址,第二个参数为源地址,第三个参数是要拷贝的字节数
S->next++;
return ( S->next-1 );
}
void* fecth( Stash* S , int index ) {
if ( index >= S->next || index < 0 )
return 0;
return &( S->storage[index * S->size] );
}
int count( Stash* S ) {
return S->next;
}
void inflate( Stash* S , int increase ) {
void* v = realloc( S->storage , ( S->quantity + increase ) * S->size );
assert(v);
S->storage = (unsigned char *)v;//书上原来是v的,但在C++中是无法通过编译的,所以强制转换了
S->quantity += increase;
}
//在C中,可将void*赋给其他任何的指针,而且编译器能够通过.但在C++中,这个语句是不允许的.在C中,void*是(malloc,realloc,calloc的返回),而不需计算.C对类型不挑剔,所以它允许这种事情.但
//C++中对类型是严格的,允许将任何类型的指针赋给void*,但不允许将void*指针赋给其他任何类型的指针