cam*_*cam 1 c++ arrays pointers
我有一个3x3数组,我正在尝试创建一个指针,我不断得到这个数组,是什么给出的?
我如何定义指针?我已经尝试了[]和*的每个组合.
是否有可能做到这一点?
int tempSec[3][3];
int* pTemp = tempSec;
Run Code Online (Sandbox Code Playgroud)
Ste*_*sop 15
你可以做 int *pTemp = &tempSec[0][0];
如果要将3x3数组视为int*,则应该将其声明为a int[9]
,并使用tempSec[3*x+y]
而不是tempSec[x][y]
.
或者,也许你想要的是int (*pTemp)[3] = tempSec
什么?那将是指向tempSec的第一个元素的指针,第一个元素本身就是一个数组.
实际上,您可以使用指向2D数组的指针:
int (*pTemp)[3][3] = &tempSex;
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
(*pTemp)[1][2] = 12;
Run Code Online (Sandbox Code Playgroud)
这几乎肯定不是你想要的,但在你的评论中,你确实要求它......
它更容易使用typedef
typedef int ThreeArray[3];
typedef int ThreeByThree[3][3];
int main(int argc, char* argv[])
{
int data[3][3];
ThreeArray* dPoint = data;
dPoint[0][2] = 5;
dPoint[2][1] = 6;
// Doing it without the typedef makes the syntax very hard to read.
//
int(*xxPointer)[3] = data;
xxPointer[0][1] = 7;
// Building a pointer to a three by Three array directly.
//
ThreeByThree* p1 = &data;
(*p1)[1][2] = 10;
// Building a pointer to a three by Three array directly (without typedef)
//
int(*p2)[3][3] = &data;
(*p2)[1][2] = 11;
// Building a reference to a 3 by 3 array.
//
ThreeByThree& ref1 = data;
ref1[0][0] = 8;
// Building a reference to a 3 by 3 array (Without the typedef)
//
int(&ref2)[3][3] = data;
ref2[1][1] = 9;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4817 次 |
最近记录: |