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
.