Copying bytes using for loop

I'm trying to implement a growth function that initializes new byte array same as old, and share to 0 for new bits. For instance, if my old size is 12 and I set 4 to 1
then I will get this:
0000100000000000
0123456789012345

If I use my growth function and my new size is 24, I should expect this:
000010000000000000000000
012345678901234567890123

I'm trying to use a for loop. I also need to copy the old bytes to new bytes through the old byteArraySize_. So far my code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  void BitVector::Growth (size_t newsize)
  {
 // increase number of bits, retaining current values
    uint8_t * newByteArray;
    size_t newByteArraySize;


    newByteArraySize = (newsize + 7) / 8;
    newByteArray = new uint8_t[newByteArraySize];
    //  delete[] byteArray_;
    byteArraySize_ = newByteArraySize;
    //delete[] byteArray_;
    byteArray_ = newByteArray;

 for (size_t i = 0; i > byteArraySize_; ++i)
      {
        Unset(i); //makes bit 0
        newByteArray[i] = byteArray_[i];
      }
   }

There is a useful function to do just this.

 
#include <algorithm> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void BitVector::Growth (size_t newsize)
{
  uint8_t * newByteArray;
  size_t newByteArraySize;

  newByteArraySize = (newsize + 7) / 8;
  newByteArray = new uint8_t[newByteArraySize];

  std::fill(
    std::copy( byteArray_, byteArray_+byteArraySize_, newByteArray ),
    newByteArray+newByteArraySize
  );

  delete[] byteArray_;
  byteArray_ = newByteArray;
  byteArraySize_ = newByteArraySize;
}

If you want to use the same algorithm for both growth and shrinkage, you’ll need to change line 10 to work on the minimum of the two array sizes instead.

    byteArray_+std::min(byteArraySize_,newByteArraySize)

Hope this helps.
I need to use a for loop. How would I do it use a for loop?
Is this a class assignment? You are required to use a loop?

Just use a loop:

1
2
3
4
5
6
7
8
9
  size_t n = 0;
  for (; n < byteArraySize_; ++n)  // copy elements loop
  {
    newByteArray[n] = byteArray_[n];
  }
  for (; n < newByteArraySize; ++n)  // zero remaining elements loop
  {
    newByteArray[n] = 0;
  }
Thank you that helped a lot.
Topic archived. No new replies allowed.