Question

I'm in a situation where I need to make a byte array buffer that I can update throughout the life a of program. If I have two C arrays

 unsigned char buffer[1400]; 
 unsigned char data[64];

the data array values will be changing continually through out the program and getting passed through various loops (64 will always be the max length) at which point a range of its values will be added to the buffer array. So for example say that the data array has 64 different hex values in it and I want to add to the buffer a certain range of these values. This is where I get stuck, my data array looks like this..

data[64] = {0x00, 0xeb, 0xff, etc...}

In C# I would do the following to select the range I want and add it to the buffer

buffer.AddRange(data.Skip(6).Take(30));

But I'm completely lost on how to do this in C. I am really new to the language, looking through SO I see people mentioning you would use realloc but I'm still trying to wrap my head around how that works. I would greatly appreciate some guidance, hopefully I have provided enough info. Thanks!

EDIT NOTE: The buffer arrays size of 1400 is just the actual max that it will ever be, technically it could be a dynamic range anywhere between there. Would setting its max even if it never reaches that much cause any sort of issue?

Was it helpful?

Solution 2

Looks like you want something like

 #include <string.h>
 ...
 /* sizeof data is 64 if data is an array[64] of (unsigned) char */
 memcpy (&buffer[6], data, sizeof data);

This copies all the 64 data octets to the 7th buffer byte and following. If you want to copy less data,

 memcpy (&buffer[6], &data[42], 3);

copies the three bytes starting with data[42].

OTHER TIPS

First you will need to keep track how full your buffer already is:

size_t buffer_length = 0;

Then you can just use memcpy to copy your data:

memcpy(buffer + buffer_length, data + offset, bytes_to_copy);

If you are sure you need an array with dynamic size then look at

void *realloc(void *ptr, size_t size);

In this case 'buffer' should be defined as a pointer, not as a fixed size array, then you will allocate some initial size and reallocate as needed.

The realloc solution is scalable to any size of array. However, if you are sure that 1400 bytes is biggest size you will ever need, then defining that on stack will make no harm.

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