0

We know that for int array[5]; &array is int (*)[5] and we can assign and use them as

int array[5] = {1,2,3,4,5};
int (*p)[5] = &array;
// to access first element
printf("%d", p[0][0]);

This above code is for 1D array.

How to use this pointer to array approach to access 2D or n-D arrays? What will be &array for int array[n][n]?

devumesh
  • 41
  • 4
  • 1
    "*What will be `&array` for `int array[n][n]`*" - `int (*p)[n][n]` – Ruks Aug 03 '21 at 04:04
  • [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) covers array pointers and examples of how to use them with dynamic dimensions. – Lundin Aug 03 '21 at 09:53

2 Answers2

0

Generally, if p is pointer name,i row number and j column number,

  1. (*(p+i)+j) would give a memory address of a element in 2D array. i is row no. and j is col no.,
  2. *(*(p+i)+j) would give the value of that element.
  3. *(p+i) would access the ith row to access columns, add column number to *(p+i). You may have to declare the pointer as (*p)[columns] instead of just *p. Doing so, you are declaring pointer to an 2D array.

Using pointer arithmetic is treating 2d array like 1D array. Initialize pointer *Ptr to first element (int *Ptr = *data) and then add an no. (Ptr + n) to access the columns. Adding a number higher than column number would simply continue counting the elements from first column of next row, if that exists. Source

HiEd
  • 160
  • 3
-2

The & operator simply returns a pointer to the whole array, so for example you can assign it to be the first part of a 1-level higher dimension array. To understand this, we can show the difference by this code snippet:

int array[5] = {1, 2, 3, 4, 5};
printf("array address: %p\n&array address: %p\n", array, &array);
/* now test incrementing */
printf("array+1 address: %p\n&array+1 address: %p\n", array+1, &array+1);

A sample output of the above code is:

array address: 0x7fff4a53c310
&array address: 0x7fff4a53c310
array+1 address: 0x7fff4a53c314
&array+1 address: 0x7fff4a53c324

As you can see, if we increment the array pointer, it increments address by four (As Integer takes 4-bytes in my compiler). And if we increment the &array pointer, it increments by 20 that is 0x14.