简体   繁体   English

C:指向二维数组的指针

[英]C: Pointer to 2-dimensional array of pointers

I am trying to solve the following issue but could not succeed yet: 我正在尝试解决以下问题,但尚未成功:

I have a two-diwmensional array of pointers: 我有一个二维数组的指针:

int* a[16][128];

Now I want to make a pointer to this array in that way that I can use pointer arithmetic on it. 现在,我想以这种方式创建一个指向该数组的指针,以便可以对它使用指针算术。 Thus, something like this: 因此,如下所示:

ptr = a;
if( ptr[6][4] == NULL )
  ptr[6][4] = another_ptr_to_int;

I tried already some variations but it either fails then on the first line or on the if condition. 我已经尝试了一些变体,但是它要么失败,然后在第一行,要么在if条件下。

So, how can it be solved? 那么,如何解决呢? I would like to avoid template classes etc. Code is for a time critical part of an embedded application, and memory is very limited. 我想避免使用模板类等。代码是嵌入式应用程序中时间紧迫的部分,并且内存非常有限。 Thus, I would like ptr to be only sizeof(int*) bytes long. 因此,我希望ptr只有sizeof(int*)个字节长。

A pointer to the first element of the array (which is what you want) could be declared as 指向数组第一个元素的指针(这就是您想要的)可以声明为

int* (*ptr)[128];

A pointer to the array itself would be 指向数组本身的指针将是

int* (*ptr)[16][128];

and is not what you're looking for. 并不是您要找的东西。

Thing you seem to want: 您似乎想要的东西:

int* (*ptr)[128] = a; 

Actual pointer to the array: 实际指向数组的指针:

int* (*ptr)[16][128] = &a;

To start with array pointer basics for a 1D array, [tutorialspoint][1] has a very easy to ready description. 要开始使用一维数组的数组指针基础知识,[tutorialspoint] [1]的描述非常容易。 From their example: 从他们的例子:

    #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;
}

There are a couple of relavent Stack overflow answers that describe 2D arrays: How to use pointer expressions to access elements of a two-dimensional array in C? 有几个描述2D数组的relavent Stack溢出答案: 如何使用指针表达式访问C中的二维数组的元素?

Pointer-to-pointer dynamic two-dimensional array 点对点动态二维数组

how to assign two dimensional array to **pointer ? 如何将二维数组分配给指针?

Representing a two-dimensional array assignment as a pointer math? 将二维数组分配表示为指针数学吗?

  [1]: https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM