[圖解C] Example 722: dynamic allocation of 2D array

// Example 722: dynamic allocation of 2D array
// array[n][m]
//   type **pointer = (type**)malloc(n*sizeof(type*));
//     pointer[0] = (type*)malloc(m*sizeof(type));
//     pointer[1] = (type*)malloc(m*sizeof(type));
//     pointer[.] = (type*)malloc(m*sizeof(type));
//     pointer[m-1] = (type*)malloc(m*sizeof(type));
//
// using "for" loop to product pointer in (n x m)

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int **ptr;
    int row, col;
    int i, j, count=0;
 
    printf("enter the number of row: ");
    scanf("%d", &row);
    printf("enter the number of column: ");
    scanf("%d", &col);
 
    // using for loop to product pointer[row][col]
    ptr = (int**)malloc(row*sizeof(int*));
    for (i=0 ; i<row ; i++){
        ptr[i] = (int*)malloc(col*sizeof(int*));
        for (j=0 ; j<col ; j++){
            count++;
            ptr[i][j] = count;    // assign a value to pointer[i][j]
        }
    }
 
 
    for (i=0 ; i<row ; i++){
        for (j=0 ; j<col ; j++){
            printf("%d\t", ptr[i][j]);
            // the content of pointer ptr[i][j] dep on %d
        }
        printf("\n");
    }
 
    system("pause");
    return 0;
}