Question

If I have two arrays

unsigned char buffer[80];
unsigned char data[3]

// data array will always hold hex values
data[] = {0x00, 0xEB, 0xFF}

If I wanted to keep updating the buffer array by appending the elements of data[] (which will always be hex values) on to the end of it what would be the best way to do this since I know what the max size of the buffer array can be? Also, what would need to change if I did not know what the max size of the buffer array would be and need to update that as I'm adding to it?

Thanks!

Was it helpful?

Solution

Just keep track of the number of bytes already in the buffer array. It starts out at zero, and for every byte you append you increase this counter by one. This means that not only do you know the number of bytes in the array, the counter is also the the next position to add to.

So if the counter is zero, then you set buffer[0] and increase the counter to one. Then to append the next byte you set buffer[1] and increase the counter to two, etc.


To continually append the data array in a loop, use memcpy and increase the counter by the number of items in data:

size_t count = 0;  /* Counter starts out at zero */

/* Append the `data` array five times */
for (size_t i = 0; i < 5; ++i)
{
    /* Use of `sizeof` here assumes that `data` is a proper array and not a pointer */
    memcpy(&buffer[count], data, sizeof(data));

    /* Increase counter */
    count += sizeof(data);
}

Note: The code assumes that both buffer and data are arrays of char (or other 8-bit types).

Also take care that you don't write beyond the bounds of the buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top