I know that we can achieve dynamic multi-dimensional arrays using pointers and there are many ways to do it, with single pointers and double pointers as well. But while exploring on this topic, came across this piece of code in which I am not able to understand the head and tail. Can anyone please explain me how the below piece of code works?
Also please explain,
1) Why it is necessary to allocate r*sizeof(int*)
to arr
when we are anyways going to allocate memory to arr[i]
as r*c*sizeof(int)
.
2) Why it is necessary to do arr[i] = *arr+c*i
.
Since I am very new to this dynamic memory allocation and so much eager to dig little deeper, arised these questions. Sorry if it is basic but still I have no idea about it. Thanks,
#include<stdio.h>
#include<stdlib.h>
int main()
{
int r=3, c=4;
int **arr;
int count = 0,i,j;
arr = (int **)malloc(sizeof(int *) * r);
arr[0] = (int *)malloc(sizeof(int) * c * r);
for(i = 0; i < r; i++)
arr[i] = (*arr + c * i);
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
arr[i][j] = ++count; // OR *(*(arr+i)+j) = ++count
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
{
printf("%d, %p, %p\n", arr[i][j], &arr[i][j], arr[i]);
}
return 0;
}
Output:
1, 21100, 21100
2, 21104, 21100
3, 21108, 21100
4, 2110c, 21100
5, 21110, 21110
6, 21114, 21110
7, 21118, 21110
8, 2111c, 21110
9, 21120, 21120
10, 21124, 21120
11, 21128, 21120
12, 2112c, 21120