I passed a array to function and tried to find the length of the array . but the result was not expected . can anybody explain please?
int main()
{
int array[10]={0};
func(array);
return 0;
}
void func(int arr[])
{
printf("length of an array is %d ",(sizeof(arr)/sizeof(arr[0]));
}
it gives the answer 2. when I tried the same operation inside main function it works fine (answer is 10). //using gcc complier in linux
You are sending and recieving a array pionter, not the array.
while sending arg::
While Receiving arg:
But it's not good to send the total array. So send and receive arguments like below.
When you pass an array into a function as a parameter, the array decays into a pointer to the beginning of the array. A pointer has no meta information stored in it unlike the array. A good practice is to pass the size to the function as an additional parameter.
Here's what C standard says (C99 6.3.2.1/3 - Other operands - Lvalues, arrays, and function designators):
So, once you pass it to the function - Inside the function, it's no more an array, it's a pointer.
is the size of a pointer, not the size of the block
arr
points to.Seems to me that the result is caused because
sizeof(arr) == 8
(size of a pointer on your PC) andsizeof(arr[0]) == 4
because it is an integer hence8/4==2
.This declaration:
void func(int arr[])
tells the function to expect a pointer to int as argument.It is not clear to me whether is possible to calculate the
sizeof
an array by reference.C
functions accepting array reference as arguments always tend to receive their length too as argument.The difference with
main()
function is that insidemain
array
variable is of typeint[10]
, thussizeof
is able to get its length in bytes. Infunc
,arr
is of typeint*
sosizeof
gives you only the length in bytes of a pointer.You have to remember that arrays decays to pointers. That means that in the function
func
the variablearr
is not actually an array but a pointer. And doingsizeof
on a pointers returns the size of the pointer and not what it points to.You get the result
2
because you're on a 64-bit system where pointers are 64 bits (i.e. 8 bytes), an when divided by the size ofint
(which is 4 bytes) you get the result2
.sizeof() operator returns the size of the data type. here int size is two.