C硬编码数组作为memcpy参数 [英] C hardcoded array as memcpy parameter

查看:72
本文介绍了C硬编码数组作为memcpy参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个硬编码的char数组作为 source 参数传递给memcpy ...类似这样的东西:

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

使用clang编译时出现以下错误:

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

clang给出的错误是:

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

所以,这个问题:

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

How do I pass in a hardcoded array as the source parameter of 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)

还有一些我想在这里写的疯狂组合...

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.

推荐答案

如果使用C99或更高版本,则可以使用复合文字.( N1256 6.5.2.5)

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

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

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

要点是:

  • 将数组设为const,否则将拒绝使用临时数组的地址.
  • 将数字快速转换为 char ,否则缩小的转换将被拒绝.
  • 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.

这篇关于C硬编码数组作为memcpy参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆