I am recently studying pointers and arrays. Suppose I initialize an array like
int a[4]={6,2,3,4};
Now after reading a lot ,I understand that
1) a
and &a
will point to same location.But they aren't pointing to the same type.
2) a
points to the first element of the array which is an integer value so the type of a is int*
.
3) &a
points to an entire array(i.e an integer array of size 4) therefore the type is int (*)[]
.
Now what I actually don't get is how to use these type??
For Example: CODE 1:
#include<stdio.h>
void foo(int (*arr)[4],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",*(*arr+i));
printf("\n");
}
int main()
{
int arr[4]={6,2,3,4};
foo(&arr,4);
return 0;
}
CODE 2:
#include<stdio.h>
void foo(int *arr,int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",*(arr+i));
printf("\n");
}
int main()
{
int arr[4]={6,2,3,4};
foo(&arr,4);
return 0;
}
In code 2 we are passing &arr so its type should be of int (*)[],then how come we are getting the correct output even though we are having a type int *.
I really don't understand what is the meaning of type and how to use it?
Kindly explain with some examples.