2

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

0xRyN
  • 852
  • 2
  • 13
  • If you want to copy it into certain parts of the buffer then you need to offset. Not sure what alternative you are thinking of. I guess you can keep a pointer to the next position in the buffer to write to but that still requires moving the pointer after each write. It's not very clear what your exact goal is. – kaylum Nov 30 '21 at 02:06
  • Put them all in a struct? What's the goal? Serialization? – Passerby Nov 30 '21 at 02:08
  • @Passerby FIFO work – 0xRyN Nov 30 '21 at 02:28

1 Answers1

4

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Haha that was exactly what I was doing. Guess there is nothing that can do that automatically. Thank you ! Closed* – 0xRyN Nov 30 '21 at 02:27