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;