foo(char*):使用硬编码的 {...}

问题描述 投票:0回答:1

我有一个函数

foo
需要一个
char*
。我想用硬编码来调用该函数
{0x00, 0xff}
而不先将其分配给变量。

// out of my control, uses char* as a byte array: void foo(const char*){} int main(void) { // First assigning to unsigned char (unsigned necessary for 0xff) // then casting to char* and calling works: unsigned char x[2] = {0x00, 0xff}; foo((char *)x); // foo({0x00, 0xff}); // err, cannot interpret the braces // Hint: const char foo((const char[]){0x00, 0x01}); // works! // 0xff out of char range. Must be unsigned char. foo((const char[]){0x00, 0xff}); // err return 0; }
a.cpp:10:6: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘char*’```
有什么提示吗?

c++ arrays char
1个回答
0
投票
我相信这个

foo(reinterpret_cast<const char*>((const unsigned char[]){0x00, 0xff}));
就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.