16 2DArray Pointers
16 2DArray Pointers
2D Arrays
int A[m][n];
The number of bytes: m*n*sizeof(int).
2D Arrays and #define n 2
Double Pointers #define m 3
int A[n][m];
int A[2][3]={{1,2,3},{4,5,6}};
Bryn Mawr College
CS246 Programming Paradigm For 1D array, to access array elements:
A[i]
*(A+i)
Access 2D Arrays Using Array Name Access 2D Arrays Using Array Name
int A[m][n]; int A[m][n];
We can think of A dereference of A : *A
A[0] as the address of row 0, the address of row 0 or A[0]
A[1] as the address of row 1
A[0] is an int*
In general: A[i][j] = *(A[i] + j) = *(*(A+i)+j)
A dereference of A[0] : *A[0]
Example: A[0][2] = *(A[0] + 2)
the first element of row 0 or A[0][0]
o Note that: A[0] = *A
**A = A[0][0] is an int
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**
1
4/1/14
2
4/1/14
Exercise
Write a function that int foo(char* filename, int A[], int* countptr){
takes FILE* fp=NULL;
int num=0;
o the name of a file (char*) that contains ints, if ((fp=fopen(filename, r)) != NULL){
o an array of ints while (fscanf(fp, %d,&num)>0) {
o the address of a variable count A[*countptr]= num;
*countptr += 1;
reads the file into the array. } return 0;
Assume that the array has enough space to hold the file. } else
count should be updated to the number of entries in return 1;
the file. }
3
4/1/14