I want to pass in a hardcoded char array as the source
parameter to memcpy ... Something like this:
memcpy(dest, {0xE3,0x83,0xA2,0xA4,0xCB} ,5);
This compiled with clang gives the following error:
cccc.c:28:14: error: expected expression
If i modify it to be (see the extra parenthesis ):
memcpy(dest,({0xAB,0x13,0xF9,0x93,0xB5}),5);
the error given by clang is:
cccc.c:26:14: warning: incompatible integer to pointer
conversion passing 'int' to parameter of
type 'const void *' [-Wint-conversion]
cccc.c:28:40: error: expected ';' after expression
memcpy(c+110,({0xAB,0x13,0xF9,0x93,0xB5}),5);
So, the question:
How do I pass in a hardcoded array as the source parameter of memcpy
(http://www.cplusplus.com/reference/cstring/memcpy/)
I have tried:
(void*)(&{0xAB,0x13,0xF9,0x93,0xB5}[0]) - syntax error
{0xAB,0x13,0xF9,0x93,0xB5} - syntax error
({0xAB,0x13,0xF9,0x93,0xB5}) - see above
(char[])({0xE3,0x83,0xA2,0xA4,0xCB}) - error: cast to incomplete type 'char []' (clang)
and some more insane combinations I'm shamed to write here ...
Please remember: I do NOT want to create a new variable to hold the array.
If you use C99 or later, you can use compound literals. (N1256 6.5.2.5)
#include <stdio.h>
#include <string.h>
int main(void){
char dest[5] = {0};
memcpy(dest, (char[]){0xE3,0x83,0xA2,0xA4,0xCB} ,5);
for (int i = 0; i < 5; i++) printf("%X ", (unsigned int)(unsigned char)dest[i]);
putchar('\n');
return 0;
}
UPDATE: This worked for C++03 and C++11 on GCC, but are rejected with -pedantic-errors
option. This means this is not a valid solution for standard C++.
#include <cstdio>
#include <cstring>
int main(void){
char dest[5] = {0};
memcpy(dest, (const char[]){(char)0xE3,(char)0x83,(char)0xA2,(char)0xA4,(char)0xCB} ,5);
for (int i = 0; i < 5; i++) printf("%X ", (unsigned int)(unsigned char)dest[i]);
putchar('\n');
return 0;
}
points are:
char
explicitly, or the narrowing conversion will be rejected.