Thread: byte arrays & vectors

  1. #1
    Registered User
    Join Date
    Jan 2004

    byte arrays & vectors

    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:

    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?
      // 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];
      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;
    Now, I have to change this code to store vectors. This makes me confuse.

    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.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >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
    Without more detail I would assume that the byte array stores all of the values in the vector instead of just a single value. So all you would need to do is call add for every element in the vector. Of course, this is just an assumption based on lack of information.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. brace-enclosed error
    By jdc18 in forum C++ Programming
    Replies: 53
    Last Post: 05-03-2007, 05:49 PM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  3. vectors vs c style arrays
    By markucd in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2006, 11:11 AM
  4. Converting byte arrays to vectors
    By kasun in forum C++ Programming
    Replies: 3
    Last Post: 03-02-2004, 10:31 AM
  5. error: identifier "byte" is undefined.
    By Hulag in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2003, 05:46 PM