I have an API taking some options:
void init_api(const char* options[][2]);
I am allowed to pass a NULL pointer for no options, alternatively, an options array such as this can be passed:
const char* some_options[][2] = { {"opt1", "val1"},
{"opt2", "val2"},
{0,0}
};
This works without problems:
...
init_api(some_options);
... or ...
init_api(NULL);
...
However, this fails to compile:
const char* my_options[][2] = NULL; // error C2440: 'initializing' : cannot convert from 'int' to 'const char *[][2]'
if(...) {
my_options = some_options; // error C2440: '=' : cannot convert from 'const char *[4][2]' to 'const char *[][2]'
}
init_api(my_options); // no error here
What is going on here? Can someone explain this?
To declare an empty array of array of pointers to const char, you should use:
You need to declare a pointer to an array of pointers to const char instead. I recommend using a typedef to simplify the syntax.
In C++ (it is herited from C), array can be implicitly converted to pointer (only once though, that is
char[]is compatible withchar*butchar[][]is compatible withchar*[]but not `char**). However, the variable cannot be reassigned. So here you need to use a pointer instead of an array.The
init_apioption acceptsNULLas a parameter because for the compiler, its prototype isvoid init_api(char const* (*)[2])(the first array degenerated into a pointer), andNULLis a valid pointer.