C newbie here and today I was reading about pointers and 2D arrays from a book and I came across this program
#include <stdio.h>
int main() {
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int(*p)[2];
int i, j, *pint;
for (i = 0; i <= 3; i++) {
p = &s[i];
pint = (int*)p;
printf("\n");
for (j = 0; j <= 1; j++)
printf("%d ", *(pint + j));
}
return 0;
}
I really want to know what is the purpose of (int *) p; here. From what I can understand here that p is the pointer which stores the address of the entire i th row of the 2D array but I am not being able to understand the purpose of (int *) p; and storing it in a variable pint.
pis a pointer to an array of 2 integers. Casting that toint*makes it a pointer to a single integer, so it points to the first integer in the array. This is stored in thepintvariable, which is declaredint*.This allows you to index the array by adding an offset to
pint. In theprintf()call,*(pint+j)is equivalent topint[j], so the inner loop prints each element of the row ofs.