I have to write some literals to an array, but I have just the address of the array, so I'm doing it by first creating a local array, filling it with the literals and second copy the content to the destination array. Here is an example:
void example(char *array) {
char temp[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
memcpy(array, temp, sizeof(temp));
}
This works pretty fine, but I'm searching for a way to do the same within one line instead of two. Has anyone an idea how to do this?
I'm writing this answer down because you commented that you want to do it in one line in order to avoid having "to access many pointers". But you won't. Any decent compiler will optimize this. GCC with -O1 produces this code on x86_64 for your example, unchanged. It doesn't even call memcpy:
example:
.LFB12:
.cfi_startproc
movb $1, (%rdi)
movb $2, 1(%rdi)
movb $3, 2(%rdi)
movb $4, 3(%rdi)
movb $5, 4(%rdi)
movb $6, 5(%rdi)
movb $7, 6(%rdi)
movb $8, 7(%rdi)
ret
.cfi_endproc
To explain: $1, $2 etc are elements of your literal, and %rdi is the register that contains the first argument to example i.e. the pointer you named array.
Just use the two readable lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With