Dynamic allocation of 2D array
Recap: Dynamic allocation of 1D array
int n = 6;
int *ptr = (int*)malloc(n*sizeof(int));
Creates an int array of size n(=6), dynamically.
This may be visualized as follows:
ptr
Dynamic allocation of many 1D arrays
int n = 6;
int *ptr1 = (int*)malloc(n*sizeof(int));
int *ptr2 = (int*)malloc(n*sizeof(int));
int *ptr3 = (int*)malloc(n*sizeof(int));
int *ptr4 = (int*)malloc(n*sizeof(int));
Creates four int arrays of size n(=6), dynamically.
This may be visualized as follows:
Dynamic allocation of many 1D arrays
ptr1
ptr2
ptr3
ptr4
Since data types of ptr1 to ptr4 are same,
they can be given togetherness:
ptr1
ptr2
ptr3
ptr4
An array of pointers can be created, dynamically:
ptr1
ptr2
ptr3
ptr4
An array of pointers can be created, dynamically:
int m = 4;
int **ptr = (int**)malloc(m*sizeof(int*));
ptr
How four arrays can be created, dynamically, size
of each array being six:
int m = 4, n = 6, k;
int **ptr = (int**)malloc(m*sizeof(int*));
for(k=0; k<m; k++)
ptr[k] = (int*)malloc(n*sizeof(int));
Effect of which may be visualized as follows:
n
ptr
ptr[0]
ptr[1]
ptr[2]
ptr[3]
int m = 4, n = 6, k, j;
int **ptr = (int**)malloc(m*sizeof(int*));
for(k=0; k<m; k++)
ptr[k] = (int*)malloc(n*sizeof(int));
//now you may use ptr like a 2D array
for(k=0; k<m; k++)
for(j=0; j<n; j++)
scanf("%d", &ptr[k][j]);