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?
A pointer to pointers is not the same as a pointer to arrays.
(In particular, notice how
sizeof(*ptr1)
issizeof(char)*6
, whereassizeof(*ptr3)
issizeof(char*)
— this has serious ramifications for pointer arithmetic.)new char[5][10]
gives you achar (*)[10]
(which has absolutely nothing to do with function pointers, by the way), because the pointers and chars are laid out in that fashion in memory (my second example).This is not the same as
char**
(which represents a different layout), so a conversion between the two makes no sense; hence, it is disallowed.So your function's return type must be
char (*)[10]
:Of course, this is really ugly, so you're far better off with a
std::vector<std::string>
.This FAQ entry explains it best, under the title "Conversions".
char**
is not the same type aschar (*)[10]
. Both of these are incompatible types and sochar (*)[10]
cannot be implicitly converted tochar**
. Hence the compilation error.The return type of the function looks very ugly. You have to write it as:
Now it compiles.
Or you can use
typedef
as:Ideone.
Basically,
char (*v)[10]
defines a pointer to achar
array of size 10. It's the same as the following:So your code becomes equivalent to this:
cdecl.org
helps here:char v[10]
reads asdeclare v as array 10 of char
char (*v)[10]
reads asdeclare v as pointer to array 10 of char
Because
char**
andchar (*)[10]
are two different types.char**
is a pointer to pointer(tochar
), whilechar (*)[10]
is a pointer to an array(of size 10) ofchar
. Resultantly, the moving step ofchar**
issizeof(void *)
bytes which is 4 bytes on win32 platform, and the moving step ofchar (*)[10]
issizeof(char) * 10
bytes.Example
Output
To use
char (*)[10]
as a function's return type(or as input/output parameter of the function), the easiest and most readable way is to use atypedef
:Note that it can easily be mixed up with
typedef
of an array of pointers, if not careful:Reference
Arrays and Pointers