问题描述
我知道这是一个非常基本的问题,但没有数量的谷歌清除这对我。这就是为什么在这里发布。
在c ++中考虑声明 int x [10];
I know that this is a very basic question but no amount of googling cleared this for me. That's why am posting it here.In c++ consider the declaration int x[10];
这是一个1维数组其中x是基本指针,它包含数组的第一个元素的地址。所以 x
给我的地址和 * x
给出第一个元素。
This is a 1-dimensional array with x being the base pointer that is it contains the address of the first element of the array. So x
gives me that address and *x
gives the first element.
类似的声明
int x[10][20];
这里是什么样的变量 x
当我做
what kind of variable is x
here. When i do
int **z = x;
编译器说它不能转换 int(*)[ code>到
int **
.And为什么 cout 和
cout<< * x;
给出相同的值
如果我声明一个指针数组为
the compiler says it cannot convert int (*)[20]
to int **
.And why does cout<<x;
and cout<<*x;
give the same value??And also if i declare an array of pointers as
int *p[10];
那么 x
p
(在他们的类型)?因为当一个声明 int x [10]
和 int * p
> x 到 p
但是在二维数组的情况下不是这样?为什么?
有人可以为我清除这个或者提供一个很好的资源材料。
then is there a difference between x
and p
( in their types) ?? because when one declares int x[10]
and int *p
then it is valid to assign x
to p
but it is not so in case of two dimensional arrays? why?Could someone please clear this for me or else provide a good resource material on this.
推荐答案
数组和指针同样的事情。在C和C ++中,多维数组只是数组数组,没有涉及指针。
Arrays and pointers aren't the same thing. In C and C++, multidimensional arrays are just "arrays of arrays", no pointers involved.
int x[10][20];
是一个10个数组的数组,每个数组包含20个元素。如果在上下文中使用 x
,它将衰减为指向其第一个元素的指针,那么最终将获得一个指向这些20个元素数组之一的指针 - int(*)[20]
。请注意,这样的事情不是指向指针的指针,因此无法进行转换。
Is an array of 10 arrays of 20 elements each. If you use x
in a context where it will decay into a pointer to its first element, then you end up with a pointer to one of those 20-element arrays - that's your int (*)[20]
. Note that such a thing is not a pointer-to-a-pointer, so the conversion is impossible.
int *p[10];
是一个10指针的数组,所以是不同于x。
is an array of 10 pointers, so yes it's different from x.
特别是,你可能有麻烦,因为你似乎认为数组和指针是一样的 - 你的问题说:
In particular, you may be having trouble because you seem to think arrays and pointers are the same thing - your question says:
这不是真的。一维 x
是一个数组,它只是在一些上下文中数组衰减为指向其第一个元素的指针。
Which isn't true. The 1-dimensional x
is an array, it's just that in some contexts an array decays into a pointer to its first element.
阅读,了解有关此主题的所有内容。
Read the FAQ for everything you want to know about this subject.
这篇关于指针和多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!