这可能是一个愚蠢的问题,但我不明白为什么会这样:
int** test = new int*[7];
int x = 7;
*(test+1) = &x;
cout << (**(test+1));
Run Code Online (Sandbox Code Playgroud)
test是一个指向指针的指针吗?第二个指针指向数组,对吗?据我所知,我需要先取消引用"test"指针才能找到具有数组的指针.
(*test) // Now I have int*
*((*test) + 1) // to access the first element.
Run Code Online (Sandbox Code Playgroud)
我的错误思考在哪里?
And*_*rsK 12
int**test = new int*[7];
+------++------++------++------++------++------++------+
| int* || int* || int* || int* || int* || int* || int* |
+------++------++------++------++------++------++------+
Run Code Online (Sandbox Code Playgroud)
是一个带有int指针的数组的等价物:
int* test[0]
int* test[1]
...
int* test[6]
Run Code Online (Sandbox Code Playgroud)
这个
int x = 7;
*(test+1) = &x;
+------++------++------++------++------++------++------+
| int* || &x || int* || int* || int* || int* || int* |
+------++------++------++------++------++------++------+
Run Code Online (Sandbox Code Playgroud)
是相同的
int x = 7;
test[1] = &x
Run Code Online (Sandbox Code Playgroud)
所以现在原始数组中的一个指针指向x的内存位置
cout << (**(test+1));
Run Code Online (Sandbox Code Playgroud)
是相同的
cout << *test[1]
Run Code Online (Sandbox Code Playgroud)
这是x(== 7)的值,并且测试[1]和&x都指向.
您是否认为自己已经创建了一个指向7
int 数组的指针?你没有.实际上你已经创建了一个7
指向int 的指针数组.所以这里没有指向数组的"第二指针".只有一个指针指向7个指针中的第一个(test
).
然而,随着*test
你获得了尚未初始化的第一个指针.如果你想补充1
到说,你会增加1
一些随机地址.但是如果你添加1
到test
你得到一个指向数组的第二个指针的指针.而dererencing 那你得到的第二指针,你没有初始化.
您所描述的内容将通过不同的语法实现
typedef int array[7];
array* test = new int[1][7];
// Note: "test" is a pointer to an array of int.
// There are already 7 integers! You cannot make it
// point to an int somehow.
*(*test + 1) = 7;
int *p1 = *test
int i1 = *(p1 + 1); // i1 is 7, second element of the int[7]
delete[] test;
Run Code Online (Sandbox Code Playgroud)
不使用typedef,这看起来如下所示
int(*test)[7] = new int[1][7];
Run Code Online (Sandbox Code Playgroud)
也就是说,您已经创建了一个单元素数组,其中元素类型是一个7元素的int数组.new
给你一个指向该数组的指针.请注意,括号很重要:*
优先级低于[7]
,否则这将被视为指向整数的7指针的数组.
归档时间: |
|
查看次数: |
17925 次 |
最近记录: |