我有一个第三方库,它的函数声明如下:
void foo(const void* input, char output[1024]);
如果我写这样的东西:
char* input = "Hello";
char output[1024];
foo(input, output); // OK
但我不想在堆栈上声明这么大的数组(这在操作系统内核环境中会非常危险)。所以我必须做这样的事情:
char* input = "Hello";
char* output_buf = new char[1024];
foo(input, output_buf); // Compiler Error C2664
我无法更改 foo 的实现。我该怎么办?
==================
问题已解决。我的真实代码是这样的:
char* input = "Hello";
void* output_buf = new char[1024];
foo(input, output_buf); // Compiler Error C2664
标准不隐式接受从 void* 到 char* 的转换。所以下面的代码可以工作:
char* input = "Hello";
void* output_buf = new char[1024];
foo(input, (char*)output_buf); // OK
最佳答案
这很奇怪,因为在 C++ 中,任何数组类型的函数参数实际上都被视为指针类型,即编译器看到的“真实”函数签名是
void foo(const void* input, char* output);
After determining the type of each parameter, any parameter of type “array of T” [...] is adjusted to be “pointer to T” (C++11, [dcl.fct], ¶5)
最重要的是,您的代码确实可以工作,如您所见 here ;您确定您的“缩小范围”示例确实反射(reflect)了您所看到的问题吗?问题可能出在另一个参数的类型上。
关于c++ - 如何将指针作为数组参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13903524/