Search code examples
cbuffermemcpy

C : memcpy to the "end" of a buffer


I got a giant buffer and I need to write strings and ints to it.

I know you can write to it using memcpy / memmove. But in that case, I'd have to offset each variable.

Example :

int a = 10;
char *s = "hello world";
char buf[100];
memcpy(buf, a, 4);
memcpy(buf + 4, s, strlen(s))

As you can see I need to offset + 4 to the second memcpy for it to work.

I got tons of variables. I don't want to offset each one of them. Is it possible to do so ?

PS : the buffer is exactly the size of the sum of all variables


Solution

  • You can keep the current offset in a separate variable and increase it for each value you copy in.

    int a = 10;
    char *s = "hello world";
    
    char buf[100];
    int offset = 0;
    
    memcpy(buf + offset, &a, sizeof(a));
    offset += sizeof(a);
    memcpy(buf + offset, s, strlen(s))
    offset += strlen(s);
    

    This also has the advantage that you can reorder fields by moving pairs of lines around without having to renumber anything.