thinking in c+的问题
#include<cassert>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
const int increment=100;
typedef struct CStashTag
{
int size;
int quantity;
int next;
unsigned char* storage;
}CStash;
void initialize(CStash* s,int size);
void cleanup(CStash* s);
int add(CStash* s,const void* element);
void* fetch(CStash* s,int index);
int count(CStash* s);
void inflate(CStash* s,int increase);
void initialize(CStash* s,int sz)
{
s->size=sz;
s->next=0;
s->quantity=0;
s->storage=0;
}
int add(CStash* s,const void* element)
{
if(s->next>=s->quantity)
inflate(s,increment);
int startBytes=s->next*s->size;
unsigned char* e=(unsigned char*)element;
for(int i=0;i<s->size;i++)
s->storage[startBytes+i]=e[i];
s->next++; //这里应该++
return (s->next-1);
}
void* fetch(CStash* s,int index)
{
assert(0<=index);
if(index>=s->next)
return 0;
return &(s->storage[index* s->size]);
}
int count(CStash* s)
{
return s->next;
}
void inflate(CStash* s,int increase)
{
assert(increase>0);
int newQuantity=s->quantity+increase;
int oldBytes=s->quantity * s->size;
int newBytes=newQuantity * s->size;//这里楼主写错了
unsigned char* b=new unsigned char[newBytes];
for(int i=0;i<oldBytes;i++)
b[i]=s->storage[i];
delete [](s->storage);
s->storage=b;
s->quantity=newQuantity;
}
void cleanup(CStash *s)
{
if(s->storage!=0)
{
cout<<"freeing storage"<<endl;
delete [](s->storage);
}
}
int main()
{
CStash intStash,stringStash;
int i;
char* cp;
ifstream in;
string line;
const int bufsize=80;
initialize(&intStash,sizeof(int));
for(int i=0;i<5;i++)
add(&intStash,&i);
for(int i=0;i<count(&intStash);i++)
cout<<"fetch(&intStash,"<<i<<")="
<<*(int*)fetch(&intStash,i)<<endl;
initialize(&stringStash,sizeof(char)*bufsize);
in.open("C:\\Users\\Seffrui_M\\Desktop\\liupangshikeng.txt");
assert(in);
while(getline(in,line))
add(&stringStash,line.c_str());
i=0;
while((cp=(char*)fetch(&stringStash,i++))!=0)
cout<<"fetch(&stringStash,"<<i<<")="<<cp<<endl;
cleanup(&intStash);
cleanup(&stringStash);
return 0;
}