我可以使用C ++中的指针访问二维数组的元素吗? [英] Can I access elements of a 2D array using pointers in C++?
问题描述
对于1D数组,我可以使用数组名作为指针,并添加偏移量来访问数组的每个元素。是否有类似2D数组的东西?
我定义了一个二维数组如下:
int arr [2] [3] = {{1,2,3},{4,5,6}};
int ** arrPtr = arr;
但是我遇到了第二行的编译错误。应该不是二维数组有类型 int **
?
,并看到:
2dArray = new int * [size];
有人可以告诉我 int * [size]
意味着? ( size
是 int
,我假设)。
非常感谢。
定义为yours的多维数组只是一个指针, 。因此,您可以执行下列操作:
int arr [2] [3] = {{1,2,3} {4,5,6}};
int * arrPtr =(int *)arr;
一般来说,指向的元素的指针arr [a] [b ]
可以通过 arrPtr + a * bSize + b
访问,其中bSize是第一个数组维度的大小(在这种情况下为三)。
您的第二个问题涉及动态内存分配 - 在运行时分配内存,而不是在程序启动时定义固定金额。我建议您在处理动态分配的2D数组之前,先查看 cplusplus.com 上的动态内存分配。
For 1D array, I can use array name as a pointer and add offset to it to access each element of the array. Is there something similar for 2D arrays?
I defined a 2D array as follows
int arr[2][3] = {{1,2,3}, {4,5,6}};
int** arrPtr = arr;
but I got compiler error for the second line. Shouldn't 2D array have type int**
?
I came across another thread here:
C++ Accessing Values at pointer of 2D Array
and saw this:
2dArray = new int*[size];
Could someone please tell me what int*[size]
means? (size
is an int
, I presume).
Thanks a lot.
A multidimensional array defined as yours is is only a single pointer, because the data is encoded in sequence. Therefore, you can do the following:
int arr[2][3]={{1,2,3},{4,5,6}};
int* arrPtr = (int*)arr;
In general, the pointer to the element at arr[a][b]
can be accessed by arrPtr + a*bSize + b
where bSize is the size of the first array dimension (in this case three).
Your second question relates to dynamic memory allocation - allocating memory at runtime, instead of defining a fixed amount when the program starts. I recommend reviewing dynamic memory allocation on cplusplus.com before working with dynamically allocated 2D arrays.
这篇关于我可以使用C ++中的指针访问二维数组的元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!