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

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 type of return should be for this function to work?

+3
source share
3 answers

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

The return type of the function looks very ugly. You should write this as:

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

Now it compiles .

Or you can use typedeflike:

typedef char carr[10];

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

Ideone .


, char (*v)[10] char 10. , :

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

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

, :

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

cdecl.org :

  • char v[10] declare v as array 10 of char
  • char (*v)[10] declare v as pointer to array 10 of char
+16

.

very crude diagram

( , , sizeof(*ptr1) - sizeof(char)*6, sizeof(*ptr3) - sizeof(char*) — .)


new char[5][10] char (*)[10] (, , ), ( ).

, char** ( ), ; , .

, char (*)[10]:

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

, , std::vector<std::string>.


"".

+13

char** char (*)[10] - . char** - ( char), char (*)[10] - ( 10) char. char** sizeof(void *) , 4 win32, char (*)[10] sizeof(char) * 10 .

   char *c = NULL;
   char **v = &c;
   cout << typeid(v).name() << endl;
   cout << (void*)v << endl;
   v += 1;
   cout << (void*)v << endl;

   char d[10];
   char (*u)[10] = &d;
   cout << typeid(u).name() << endl;
   cout << (void*)u << endl;
   u += 1;
   cout << (void*)u << endl;

char * *
0034FB1C
0034FB20
char (*)[10]
001AFC50
001AFC5A

char (*)[10] ( / ), - typedef:

// read from inside-out: PTRTARR is a pointer, and, it points to an array, of chars.
typedef char (*PTRTARR)[10];

, typedef , :

// operator[] has higher precedence than operator*,
// PTRARR is an array of pointers to char.
typedef char *PTRARR[10];

+5

All Articles