Easiest way to repeat a sequence of bytes into a larger buffer in C++

I would probably just go with this:

for (int i=0; i < N; ++i)
    memcpy(buffer + i * byte_sequence_length, byte_sequence, byte_sequence_length);

This assumes you are dealing with binary data and are keeping track of the length, not using '\0' termination.

If you want these to be c-strings you'll have to allocate an extra byte and add in the '\0' a the end. Given a c-string and an integer, you'd want to do it like this:

char *RepeatN(char *source, size_t n)
{
    assert(n >= 0 && source != NULL);            
    size_t length = strlen(source) - 1;
    char *buffer = new char[length*n + 1];
    for (int i=0; i < n; ++i)
        memcpy(buffer + i * length, source, length);
    buffer[n * length] = '\0';
}

Repeating the buffer while avoiding pointer arithmetic:

You can use std::vector < char > or std::string to make things easier for you. Both of these containers can hold binary data too.

This solution has the nice properties that:

  • You don't need to worry about memory access violations
  • You don't need to worry about getting the size of your buffer correct
  • You can append sequences at any time to your buffer without manual re-allocations

.

//Note this works even for binary data.
void appendSequenceToMyBuffer(std::string &sBuffer
       , const char *byte_sequence
       , int byte_sequence_length
       , int N)
{
  for(int i = 0; i < N; ++i)
      sBuffer.append(byte_sequence, byte_sequence_length);
}

//Note: buffer == sBuffer.c_str()

Alternate: For binary data using memcpy:

buffer = new char[byte_sequence_length*N];
for (int i=0; i < N; ++i)
  memcpy(buffer+i*byte_sequence_length, byte_sequence, byte_sequence_length); 
//...
delete[] buffer;

Alternate: For null terminated string data using strcpy:

buffer = new char[byte_sequence_length*N+1];
int byte_sequence_length = strlen(byte_sequence);
for (int i=0; i < N; ++i)
  strcpy(buffer+i*byte_sequence_length, byte_sequence, byte_sequence_length); 
//...
delete[] buffer;

Alternate: If you are filling the buffer with a single value:

buffer = new char[N];
memset(buffer, byte_value, N);
//...
delete[] buffer;

You can use the STL algorithm Generate:

MSDN: Generate

Tags:

C++

Stl

Boost