Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

C hardcoded array as memcpy parameter

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.

question from:https://stackoverflow.com/questions/35745385/c-hardcoded-array-as-memcpy-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('
');
    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('
');
    return 0;
}

points are:

  • Make the array const, or taking address of temporary array will be rejected.
  • Cast numbers to char explicitly, or the narrowing conversion will be rejected.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...