I have below program that acts like a stack. It receives a value, then takes 1 byte of that value at a time
to store it byte-by-byte as an array of bytes. When the storage is full it dynamically allocates more memory for the storage:
Now, I have to change this code to store vectors. This makes me confuse.Code:const int increment = 100; void Stash::initialize(int sz) { size = sz; // size of each space quantity = 0; // number of storage spaces storage = 0; // dynamically allocated array of bytes next = 0; // next empty storage } int Stash::add(const void* element) { if(next >= quantity) // Enough space left? inflate(increment); // Copy element into storage, // starting at next empty space: int startBytes = next * size; unsigned char* e = (unsigned char*)element; for(int i = 0; i < size; i++) storage[startBytes + i] = e[i]; next++; return(next - 1); } . . . . . . . . . . . . . . . . void Stash::inflate(int increase) { assert(increase > 0); int newQuantity = quantity + increase; int newBytes = newQuantity * size; int oldBytes = quantity * size; unsigned char* b = new unsigned char[newBytes]; for(int i = 0; i < oldBytes; i++) b[i] = storage[i]; // Copy old to new delete []storage; // Old storage storage = b; // Point to new memory quantity = newQuantity; }
Could you please point out what’s the difference between storing a single value as a byte array,
and storing a vector as a byte array.
And could you please give a few tips about changing the code to do this.
Thanks a bunch for reading.