Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading