且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 char** 不能成为 C++ 中以下函数的返回类型?

更新时间:2022-06-22 02:41:38

char**char (*)[10] 类型不同.这两种都是不兼容的类型,因此 char (*)[10] 不能隐式转换为 char**.因此编译错误.

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;
}

现在它编译.

或者你可以使用 typedef 作为:

Or you can use typedef as:

typedef char carr[10];

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

Ideone.

基本上,char (*v)[10] 定义了一个指向大小为 10 的 char 数组的指针.与以下相同:

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 在这里有帮助:


cdecl.org helps here:

  • char v[10] 读作 declare v as array 10 of char
  • char (*v)[10] 读作 declare v 作为指向 char 数组 10 的指针
  • 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