c - const void * 指针数组和 Visual C++

标签 c arrays pointers dynamic-memory-allocation const-correctness

我在代码片段中定义 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 *,因此数组本身不应该是常量,但其元素应该是常量,因为 formatconst 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/

相关文章:

c++ - 如何从 C 代码正确创建 DLL 并在 C++ 项目中使用它

javascript - OO JavaScript : array not getting initialized

c# - 使用数组在 C# 中制作地址簿

java - 如何从奇数和偶数数组中仅对奇数进行排序并仅显示排序后的奇数?

c - 无法将结构数组传递给 C 中的函数

c - 请帮助我理解 C 中不熟悉的结构语法

c - 在 C99 的宏中使用 true 和 false

c - 一个 POSIX 兼容的操作系统通常会扩展 C 标准库的现有实现?

C 指针差异 Char Int

c - 如果某些限制指针指向同一个对象,为什么编译器不生成警告或错误?