types int **和int [] []之间有什么区别? [英] What is difference between types int** and int[][]?
问题描述
如果以下分配有效:
int a[2] = {1,2};
int* b = a;
那么这有什么问题:
int a[2][2]={1,2,3,4};
int** b = a;
C ++给出一个错误,它不能转换 int [] []
到 int **
。如果 int []
与 int *
?
C++ gives an error that it can't convert int[][]
to int**
. What is difference between the two types if int[]
is the same as int*
?
推荐答案
简单。它只是一个编译器错误。数组很棘手。以下是规则:
Take it easy. It is only a compiler error. Arrays are pretty tricky. Here is the rule:
到此数组的元素地址
您的第一个代码段如下:
Your first snippet looks like:
int a[2] = {1,2};
因此,如果 a
在赋值的右边,它衰减到元素零的地址,这就是为什么它有类型 int *
。这会带给您
So according to the rule if a
is in the right hand side of a assignment then it decays to address of the element zero and that is why it has type int *
. This brings you to
int *b = a;
在第二个片段中,你真正拥有的是一个数组数组。 (顺便说一句,为了使它明确我已经改变了你的代码。)
In the second snippet what you really have is an array of arrays. (By the way, to make it explicit I've changed your code a bit.)
int a[2][2]={{1,2},{3,4}};
此时 a
到两个整数的数组!因此,如果你想为某些东西分配 a
,你需要这个东西具有相同的类型。
This time a
will decay to the pointer to an array of two integers! So if you would want to assign a
to something, you would need this something to have the same type.
int (*b)[2] = a; //Huh!
(这种语法可能有点令人惊讶,但只是想想一会儿, code> int * b [2]; 得到点? b
将是一个指向整数的数组!想要...)
(This syntax maybe a bit stunning to you, but just think for a moment that we have written int *b[2];
Got the point? b
would be an array of pointers to integers! Not really what we wanted...)
你可以在这里停止阅读,但你也可以继续,因为我没有告诉你所有的真相。我提到的规则有三个例外...
You could stop reading here, but you could also move on, because I have not told you all the truth. The rule I mentioned has three exceptions...
数组的值将不衰减到地址
- 数组是
sizeof $ c $的操作数c>
- array是
&
的操作数数组是一个字符串初始值字符数组
让我们更详细地解释这些异常和例子:
Let's explain these exceptions in more detail and with examples:
int a[2];
int *pi = a ; /* the same as pi = &a[0]; */
printf("%d\n", sizeof(a)); /* size of the array, not of a pointer is printed! */
int (*pi2)[2] = &a; /* address of the array itself is taken (not the address of a pointer) */
char a[] = "Hello world ";
这里不是指向Hello world的指针,而是复制整个字符串, 。
Here not a pointer to "Hello world" is copied, but the whole string is copied and a points to this copy.
有很多信息,而且很难一次性理解所有的内容,所以请抽出时间。我建议您阅读本主题的K& R,之后这本精彩的书。
There is really a lot of information and it is really difficult to understand everything at once, so take your time. I recommend you to read K&R on this topic and afterwards this excellent book.
这篇关于types int **和int [] []之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!