So i have the following situation:
void func(char ** a)
{
// Do some stuff...
}
int main()
{
const char * arr[2] = { "foo" };
arr[1] = "bar";
// I want to Cast the arr from const char ** to char **
func(arr);
}
I think func(reinterpret_cast<char**>(arr));
is a way, but i don't know if it's the best way.
Thank you!
For starters this declaration
const char * arr[2] = "foo";
is incorrect. Arrays are aggregates and initializers of their elements shall be enclosed in braces.
const char * arr[2] = { "foo" };
Used in expressions the array (with rare exceptions) is converted to pointer of the type const char **
.
This function
void func(char ** a)
{
// Do some stuff...
}
does not accepts a pointer to pointer to constant data. It means that the function can change pointed data. This in turn means that you shall not pass your array to this function.
What you could do is to allocate dynamically an array of arrays like for example
char **p = new char *[2];
for ( size_t i = 0; i < 2; i++ )
{
p[i] = new char[4];
}
strcpy( p[0], "foo" );
strcpy( p[1], "bar" );
func( p );
for ( size_t i = 0; i < 2; i++ )
{
delete[] p[i];
}
delete[] p;