The pointer in C++ points to the instance of a two dimensional array

  • 2020-05-19 05:15:10
  • OfStack

The pointer in C++ points to the instance of a 2-dimensional array

A 1-d pointer is usually represented by a pointer to the memory address where the first element of the array is located, as shown below


int ary[4][5];
int(*aryp)[5] = ary;

So ary[4] is equivalent to int(*aryp), which is understood as follows. However, parameter passing needs to know the number of arguments in 1 dimension, so one more parameter should be passed when passing. The reference of subarray can be understood as (*p), so the element is (*p)[i], as follows


void printVal(int(*aryp)[5],int irowCount){
  for (int(*p)[5] = aryp; p != aryp + irowCount;p++)
  {
    for (size_t i = 0; i < 5; i++)
    {
      cout << (*p)[i] << endl;
    }
  }
}

The disadvantage is that you need to pass the number of 1-dimensional arrays. But it's scalable.

Similarly, a 3 - dimensional array can use an array of Pointers to Pointers. Usually rarely used.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: