We can also declare pointer to array as
int (*ptr)[]; // ptr is a pointer to array.
When you do
ptr2 = myArray1;
compiler will throw you a warning message. Look boss types are not compatible.
In some context Arrays decays into pointers. Warning message is because, when arrays decays into pointers, the decayed type is pointer. In this case, when you do
ptr1 = myArray;
myArray decays into int *
.
But when you do,
ptr2 = myArray1;
myArray1
decays into pointer that is int *
, but the type of ptr2
is int (*)[]
.
In order to avoid warning, you should say
ptr2 = &myArray1; //&myArray1 returns address of array and type is int(*)[].
Why this statement is printing garbage? What is the correct statement? Can anyone explain?
printf("%d",ptr2[3]);// prints some garbage.
Yes, But why? Lets see the correct statement first...(note that index should be less than 3)
printf("myArray1[%d] = %d\n", i, (*ptr2)[2]);
We have to use (*ptr2)[i]
to print the array element. This is because, just by mentioning ptr2
, we will get the address of the array (not the address of some int
). and by de-referencing it (*ptr2)
we will get the address of 0th element
of the array.