4/1/14 ¡ 1 ¡
2D Arrays and Double Pointers
Bryn Mawr College CS246 Programming Paradigm
2D Arrays
- int A[m][n];
- The number of bytes: m*n*sizeof(int).
- For 1D array, to access array elements:
- A[i]
- *(A+i)
#define n 2 #define m 3 int A[n][m]; int A[2][3]={{1,2,3},{4,5,6}};
Access 2D Arrays Using Array Name
- int A[m][n];
- We can think of
A[0] as the address of row 0, A[1] as the address of row 1
- In general: A[i][j] = *(A[i] + j) = *(*(A+i)+j)
- Example: A[0][2] = *(A[0] + 2)
- Note that: A[0] = *A
- Hence, if A is a 2D int array, we can think of A as a
pointer to a pointer to an integer. That is, int**
Access 2D Arrays Using Array Name
- int A[m][n];
- A dereference of A : *A
- the address of row 0 or A[0]
- A[0] is an int*
- A dereference of A[0] : *A[0]
- the first element of row 0 or A[0][0]
- **A = A[0][0] is an int
int A[4][3];
For an int array A[m][n]:
address(A[i][j]) = address(A[0][0]) + (i × n + j) × size(int) A[i] is equivalent to *(A+i) &A[i][0] = &(*(A[i]+0)) = &*A[i] = A[i]
Array Equation
A00 A01 A02 A10 A11 A12 A20 A21 A22 A30 A31 A32 A==A[0] A[1] A[2] A[3]
Types
- Different types:
- &A: address of the entire array of arrays of ints, i.e int[m][n]
- &A[0]: same as A, address of the first element, i.e., int[n]
- &A[0][0]: address of the first element of the first element,
i.e., int.
- A: int (*)[n]
- *A: int *
- An array is treated as a pointer that points to the first
element of the array.
- 2D array is NOT equivalent to a double pointer!
- 2D array is "equivalent" to a "pointer to row".