So my book is explaining me pointers to an array using ts example
#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;
}
The output is Given as
1234 56
1212 33
1434 80
1312 78
No issue I am getting the same output.
My question is what was the need of using another pointer pint ?
Why can't we directly use P?
So When I tried to do it using P directly it didn't work
printf("%d ", *(p j));
I got garbage values in output, Why is this happening?
I also tried printing p and pint they are the same.
CodePudding user response:
Although p
and pint
have the same value, p 1
and pint 1
do not. p 1
is the same as (char *)p sizeof *p
, and pint 1
is the same as (char *)pint sizeof *pint
. Since the size of the object pointed to is different, the arithmetic gives different results.
CodePudding user response:
The pointer p
is declared like
int(*p)[2];
So dereferencing the pointer expression with the pointer in this call of printf
printf("%d ", *(p j));
you will get the j-th "row" of the type int[2]
of the two dimensional array that in turn will be implicitly converted to a pointer of the type int *
that will point to the first element of the j-th "row".
So instead of outputting elements of each row you will output first elements of each row that moreover results in undefined behavior when i
will be greater than 2
.