我在代码片段中定义 const void *
指针数组时遇到问题 - Visual C++ 提示我尝试的任何组合:
void *call_func_cdecl(void *func, const void *const *args, int nargs);
void vlogprintf(const char *format, va_list va) {
int nargs;
void **args;
args = malloc(...);
args[0] = format;
// fill the rest...
call_func_cdecl((void*)logprintf, args, nargs);
free(args);
}
如您所知,free
采用 void *
,因此数组本身不应该是常量,但其元素应该是常量,因为 format
是 const void *
并且它是 args
的一个元素。
到目前为止我尝试过这些:
const void **args
在
free(args)
行收到警告 C4090:“function”:不同的“const”限定符
void const **args
同上
void *const *args
出现
错误 C2166:左值在
args[0] = format
行指定 const 对象void **const args
同上
最佳答案
无法通过简单的 malloc 来分配 const 指针数组。基本类型就是它们,如果您知道自己在做什么,则可以(或多或少)安全地忽略这些错误。如果你想以“正确”的方式做到这一点,你可以尝试这样的事情(代码没有实际使用的顺序,只是随机的片段):
struct constvoid {
const void * ptr;
}
void *call_func_cdecl(void *func, struct constvoid *args, int nargs);
{
struct constvoid* args = malloc(...);
args[0].ptr = format;
//fill the other
call_func_cdecl((void*)logprintf, args, nargs);
free(args);
}
关于c - const void * 指针数组和 Visual C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14317020/