书上说二维数组在内存中实际是以一维数组的形式连续存放的,我做了个小测试结果却令我无法理解。
#include <iostream>
using namespace std;
int main() {
int a[2][2] = {{0,1},{2,3}};
cout << &a << endl;
cout << a << endl;
cout << *a << endl;
cout << a[0] << endl;
cout << **a << endl;
cout << *(a[0]) << endl;
return 0;
}
输出:
0x7fff396c0210
0x7fff396c0210
0x7fff396c0210
0x7fff396c0210
0
0
那个内存地址处保存的是自己的地址?那么两次解引用不应该还是这个地址才对吗?怎么会变成0???
黄舟2017-04-17 15:39:18
You should understand this, there is only one-dimensional array in C, but the elements of the array can be of any type, including the array itself, so there is a two-dimensional array. In this case, dereferencing an array name (in this case, the array name is a pointer to the first element of the array) results in the first element of the array, and the first element of the two-dimensional array is a one-dimensional array. , so the dereference again is the first element of this one-dimensional array. It’s the same as your *(a[0]) below.
Regarding the question you mentioned, the name of array a is a pointer to the contents of array a, and its value is the same as the address of its first element. For a two-dimensional array, the three values a, the address of a[0], and the address of a0 are the same, but their meanings are slightly different. The addresses of a and a[0] have the same meaning and are a secondary pointer. , but the address of a0 is a first-level pointer
PHPz2017-04-17 15:39:18
Monitor the following content under breakpoint debugging:
a
&a
a+0
a[0]
&a[0]
For the above problem, you must first know three things:
(1) A two-dimensional array is a one-dimensional array
This is a good proof. The addresses are output sequentially, and they are all continuous. Not much to say.
(2) What is the array address?
Start with a one-dimensional arrayint b[2]
. The array address is the address of an array name. For example, &b is the array address.
Two-dimensional int a[2][2]
, a is the two-dimensional array name, &a is the two-dimensional array address; a[0] is the array name of the first line (let’s call it the first line), &a[0] is the first The array address of the row array. Similarly, a[1] and &a[1] are the array name and array address of the second row respectively.
(3) Array names can be converted into pointers
First of all, correct one thing int b[2]
. The b here is not a pointer. Similarly, int a[2][2]
, the a inside is not a pointer, but a and b can be converted into pointers. Just because it can be converted doesn't mean it is, who told you that int is short.
Okay, to understand why your code is like this, the best way is to monitor the type directly.
Pay attention to the types of a[0] and b.