[英]Cannot convert char(*)[50] to char* in assignment
Newbie question here...why does the following code only work with a 1D array but not a 2D array? 这里的新手问题...为什么以下代码仅适用于1D数组而不适用于2D数组? Shouldn't it not make a difference whether b is pointing to the start of a 1D array or a 2D array, as long as it's a char* pointer (as it is)?
只要b是指向char *指针(照原样),b是指向1D数组还是2D数组的开头就不起作用吗? I thought that the general notation [bound1][bound2] was an equivalent of [bound1*bound2], even over the assignment operation.
我认为,即使在赋值操作中,通用符号[bound1] [bound2]等同于[bound1 * bound2]。 Help?
救命?
main() //this works fine
{
char *b;
b = new char[50];
return 0;
}
. 。
main() //but this raises the error "Cannot convert char(*)[50] to char* in assignment"
{
char *b;
b = new char[50][50];
return 0;
}
char[50];
is array of 50 elements of type char
. 是
char
类型的50个元素组成的数组。 Each element has type char
. 每个元素的类型为
char
。 So new char[50];
因此,
new char[50];
returns a pointer to first element: char *
- pointer to char
. 返回指向第一个元素的指针:
char *
-指向char
指针。
char[50][50]
is NOT array of char
. char[50][50]
不是char
数组。 It is array of arrays. 它是数组的数组。 Each element has type
char[50]
. 每个元素的类型为
char[50]
。 So new char[50][50];
因此,
new char[50][50];
returns a pointer to first element: char (*)[50]
- pointer to char[50]
. 返回指向第一个元素的指针:
char (*)[50]
-指向char[50]
指针。
Declare b
this way: 这样声明
b
:
char (*b)[50];
Test: http://ideone.com/1zJs1O 测试: http : //ideone.com/1zJs1O
If your were right with that [bound1][bound2] and [bound1*bound2] were equivalent you wouldn't have created a 2D array. 如果您认为[bound1] [bound2]和[bound1 * bound2]是对的,那么您将不会创建2D数组。 The size of allocated memory, that's what your multiplication implies, is not the problem here, it's about different data types: A 1D array is simply not a 2D array and that's what the compiler is telling you.
这就是您的乘法所暗示的,分配的内存大小在这里不是问题,它是关于不同的数据类型的:1D数组根本不是2D数组,这就是编译器告诉您的。 You should read about C++ type system and type safety.
您应该阅读有关C ++类型系统和类型安全的信息。
What is type safety and what are the "type safe" alternatives? 什么是类型安全?什么是“类型安全”替代方案?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.