Why can't char** be the return type of the following function in C++?

c, c++, char, function, return-type

Solution

`char**` is not the same type as `char (*)[10]`. Both of these are incompatible types and so `char (*)[10]` cannot be implicitly converted to `char**`. Hence the compilation error.

The return type of the function looks very ugly. You have to write it as:

char (*f())[10]
{
    char (*v)[10] = new char[5][10];
    return v;
}

Now it compiles.

Or you can use `typedef` as:

typedef char carr[10];

carr* f()
{
    char (*v)[10] = new char[5][10];
    return v;
}

Ideone.

Basically, `char (*v)[10]` defines a pointer to a `char` array of size 10. It's the same as the following:

 typedef char carr[10]; //carr is a char array of size 10

 carr *v; //v is a pointer to array of size 10

So your code becomes equivalent to this:

carr* f()
{
    carr *v = new carr[5];
    return v;
}

`cdecl.org` helps here:

- `char v[10]` reads as `declare v as array 10 of char`

- `char (*v)[10]` reads as `declare v as pointer to array 10 of char`

Problem

I have the following function in C++ : ``` char** f() { char (*v)[10] = new char[5][10]; return v; } ``` Visual studio 2008 says the following: ``` error C2440: 'return' : cannot convert from 'char (*)[10]' to 'char **' ``` What exactly should the return type to be, in order for this function to work?

Original source

Related problems