Why can#39;t char** be the return type of the following function in C++?(为什么 char** 不能成为 C++ 中以下函数的返回类型?)
问题描述
我在 C++ 中有以下函数:
I have the following function in C++ :
char** f()
{
char (*v)[10] = new char[5][10];
return v;
}
Visual Studio 2008 说明如下:
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?
推荐答案
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 charchar (*v)[10]读作declare v 作为指向 char 数组 10 的指针
char v[10]reads asdeclare v as array 10 of charchar (*v)[10]reads asdeclare v as pointer to array 10 of char
这篇关于为什么 char** 不能成为 C++ 中以下函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 char** 不能成为 C++ 中以下函数的返回类型?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
