I have a basic question related to indexing 2d arrays passed to a function in C. When I use a double pointer to pass it:
- Inside the function
printMatrix
indexingA
asA[i][j]
works if memory forA
inmain
was allocated usingmalloc
- Inside the function
printMatrix
indexingA
asA[i][j]
doesn't work if memory forA
inmain
was allocated statically (as in the commented code). I believe I should use:*(*(A+i*N)+j)
but why doesn'tA[i][j]
work when it works for the case above?
void printMatrix(int** A,int N) {
int i=0,j=0;
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
printf("%2d",A[i][j]);
}
printf("\n");
}
printf("\n");
return;
}
int main() {
//int A[6][6] = {{1,1,1,1,1,1},{2,2,2,2,2,2},{3,3,3,3,3,3},
//{4,4,4,4,4,4},{5,5,5,5,5,5},{6,6,6,6,6,6}};
int N = 6,i,j;
int **A = (int**)malloc(sizeof(int*)*N);
for(i=0;i<N;i++)
A[i] = (int*)malloc(sizeof(int)*N);
for(i=0;i<N;i++)
for(j=0;j<N;j++)
A[i][j] = i+j;
printMatrix((int**)A,N);
return 0;
}