我想将硬编码的 char 数组作为 source
参数传递给 memcpy ... 像这样:
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)
还有一些更疯狂的组合我很惭愧地写在这里......
请记住:我不想要创建一个新变量来保存数组。
最佳答案
如果您使用 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++ 的有效解决方案。
#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;
}
要点是:
- 将数组设为常量,否则获取临时数组的地址将被拒绝。
- 将数字显式转换为
char
,否则缩小转换将被拒绝。
关于C 硬编码数组作为 memcpy 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745385/