这个使用malloc
,但概念与分配一维数组的地址相同。
阅读内联评论,以便更好地理解。
#include <stdio.h>
#include <stdlib.h>
#define NCOLS 5
#define NROWS 2
void function( int (*_2D_ptr_Array)[NCOLS] , int nrows, int ncols );
//enable this to see the demo of accessing elements using pointer to an array
//disabling this will demo how to pass 2-D array and collect using pointer to an array.
//#define _DEMO_MAIN
int main()
{
// a is a pointer to an array of 5 ints
int (*a)[NCOLS];
int _2D_Array[NROWS][NCOLS] = {
{ 10, 20, 30, 40, 50},
{ 60, 70, 80, 90, 100}
};
int i,j;
#ifdef _DEMO_MAIN
printf("Enter 10 elements\n");
a = malloc(sizeof(int)*5*2);
printf("a got address at %p\n", a);
for(i=0;i<2;i++)
for(j=0;j<5;j++)
scanf("%d",a[i]+j);
//printing one dimentional array values
// *a is equivalent to a[j], when j = 0
for(j=0;j<5;j++)
printf("value %d is at addr %p\n",*(*a+j),(*a+j));
putchar('\n');
//printing multi-dimentional array values
// adding j to a[i] or *a gives the next element address in a given row.
for(i=0;i<2;i++)
for(j=0;j<5;j++)
printf("value %d is at %p\n",*(a[i]+j), a[i]+j);
#else
//a most common use of pointer to an array is to collect the 2-d array as an argument in function
function( _2D_Array, NROWS, NCOLS );
#endif
return 0;
}
void function( int (*_2D_ptr_Array)[NCOLS], int nrows, int ncols ) {
for(int r = 0; r < nrows ; r++) {
for(int c = 0; c < ncols ; c++)
printf("%d ", _2D_ptr_Array[r][c]);
printf("\n");
}
}
注意:返回检查类似scanf
和malloc
未有目的地处理的函数