2

I have a problem with defining an array of const void * pointers in ths code snippet - Visual C++ complains about whatever combination I try:

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

As you know free takes a void * so the array itself should not be constant but its elements should be becase format is a const void * and it's an element of args.

So far I tried these:

  • const void **args

    Got warning C4090: 'function' : different 'const' qualifiers at the free(args) line

  • void const **args

    Same as above

  • void *const *args

    Got error C2166: l-value specifies const object at the args[0] = format line

  • void **const args

    Same as above

alk
  • 69,737
  • 10
  • 105
  • 255
szx
  • 6,433
  • 6
  • 46
  • 67

2 Answers2

3

There is no way to allocate an array of const pointers through simple malloc. The basic types are what they are and if you know what you are doing, you can (more or less) safely disregard these errors. If you want to do it the "right" way, you may try something like this (code in no real-use order, just random snippets):

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);
}
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • Thanks. I ended up with just casting away the constness when passing `args` to `free()`, that should be safe I think. – szx Jan 14 '13 at 11:46
2

This is correct:

void const** args

I have a feeling that warning is a bug.

alk
  • 69,737
  • 10
  • 105
  • 255
Pubby
  • 51,882
  • 13
  • 139
  • 180
  • Looks like a bug to me too, especially because GCC didn't emit eny warnings with this version. – szx Jan 14 '13 at 11:48
  • "*This is correct*", I feel you are wrong. The title asks for an "*Array of const void * pointers [to void]*", which would decay to "a pointer to const pointer to void". What you show (`void const ** args`) is a "pointer to pointer to const void", which something different! – alk May 14 '18 at 10:16