Reputation: 233
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.
Upvotes: 1
Views: 86
Reputation: 101
The best way to pass arrays in to functions is a pointer and the number of elements.
Note you can pass arr
in to the function as arr
or &arr[0]
; both resolve to the same address.
#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;
}
Also, it's better to index the array, rather than addition and dereference. e.g. *(arr+i)
becomes arr[i]
.
Upvotes: 0
Reputation: 214730
Code 2 is not valid C, because a conversion between an array pointer and a pointer to int
is not a valid pointer conversion - they are not compatible types. If it works, it is because of some non-standard extension of your compiler, or possibly you just "got lucky".
Please note that the best way to pass an array to a function in modern C is this:
void foo(int n, int arr[n])
{
for(int i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
}
As part of a function parameter list, arr
will get adjusted to a pointer to the first element of the array, type int*
.
The pedantically correct version would also replace int n
and int i
with size_t
, which is the most proper type to use when describing the size of an object.
Upvotes: 1