[英]C: Pointer to 2-dimensional array of pointers
我正在嘗試解決以下問題,但尚未成功:
我有一個二維數組的指針:
int* a[16][128];
現在,我想以這種方式創建一個指向該數組的指針,以便可以對它使用指針算術。 因此,如下所示:
ptr = a;
if( ptr[6][4] == NULL )
ptr[6][4] = another_ptr_to_int;
我已經嘗試了一些變體,但是它要么失敗,然后在第一行,要么在if條件下。
那么,如何解決呢? 我想避免使用模板類等。代碼是嵌入式應用程序中時間緊迫的部分,並且內存非常有限。 因此,我希望ptr
只有sizeof(int*)
個字節長。
指向數組第一個元素的指針(這就是您想要的)可以聲明為
int* (*ptr)[128];
指向數組本身的指針將是
int* (*ptr)[16][128];
並不是您要找的東西。
您似乎想要的東西:
int* (*ptr)[128] = a;
實際指向數組的指針:
int* (*ptr)[16][128] = &a;
要開始使用一維數組的數組指針基礎知識,[tutorialspoint] [1]的描述非常容易。 從他們的例子:
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance; //Here the pointer is assign to the start of the array
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) ); // Note the post increment
}
return 0;
}
有幾個描述2D數組的relavent Stack溢出答案: 如何使用指針表達式訪問C中的二維數組的元素?
[1]: https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.