C硬编码数组作为memcpy参数

我想传入一个硬编码的字符数组作为memcpy的source参数…这样的事情:

 memcpy(dest, {0xE3,0x83,0xA2,0xA4,0xCB} ,5); 

这与clang编译给出了以下错误:

 cccc.c:28:14: error: expected expression 

如果我修改它(见额外的括号):

 memcpy(dest,({0xAB,0x13,0xF9,0x93,0xB5}),5); 

clang给出的错误是:

 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); 

所以,这个问题:

如何传入硬编码数组作为memcpy的源参数( http://www.cplusplus.com/reference/cstring/memcpy/ )

我努力了:

 (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) 

还有一些疯狂的组合,我羞于写在这里…

请记住:我不想创build一个新的variables来保存数组。

如果您使用C99或更高版本,则可以使用复合文字。 ( 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; } 

更新:这适用于GCC上的C ++ 03和C ++ 11,但拒绝与-pedantic-errors选项。 这意味着这不是标准C ++的有效解决scheme。

 #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; } 

要点是:

  • 使数组成为const,否则将取消临时数组的地址。
  • 将数字强制转换为char ,否则缩小的转换将被拒绝。

你可以发送一个string作为参数。 它似乎编译得很好。

 #include <iostream> #include <string.h> using namespace std; int main() { char dest[6] = {0}; memcpy(dest,"\XAB\x13\XF9\X93\XB5", 5); return 0; } 

最好的解决办法是不要这样做,而是使用一个临时variables:

 const char src[] = {0xE3,0x83,0xA2,0xA4,0xCB}; memcpy(dest, src, sizeof(src)); 

这个代码是最容易维护的,因为它不包含“幻数”,所以它不会包含任何丢失的数组项或数组越界错误,就像复合文字版本可以。

此代码也与C ++和C90兼容。

这里最重要的是要认识到生成的机器代码无论如何都是相同的。 不要以为你正在使用复合文字进行任何forms的优化。

您可以使用复合文字 。

 int main() { unsigned char dest[5]; size_t i; memcpy(dest, (unsigned char[]){0xE3,0x83,0xA2,0xA4,0xCB} ,5); printf("Test: " ); for(i=0; i<sizeof(dest)/sizeof(dest[0]); i++) printf("%02X - ", dest[i] ); printf("\n"); return 0; }