C hardcoded array as memcpy parameter

时间:2016-03-02 11:03:40

标签: c arrays hardcoded

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.

4 个答案:

答案 0 :(得分:40)

如果您使用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;
}
分数是:

  • 使数组const或临时数组的地址被拒绝。
  • 明确地将数字转换为char,否则将拒绝缩小转化。

答案 1 :(得分:23)

您只需发送一个字符串作为参数即可。它似乎编译得很好。

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    char dest[6] = {0};
    memcpy(dest,"\XAB\x13\XF9\X93\XB5", 5);

    return 0;
}

答案 2 :(得分:18)

最好的解决方案根本不是这样做,而是使用临时变量:

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

此代码是最易维护的,因为它不包含&#34;魔术数字&#34;,因此它不会包含任何丢失的数组项或数组输出错误,就像复合文字版本一样。

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

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

答案 3 :(得分:10)

您可以使用Compound Literals

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