+ 5

Why am getting wrong output?

This code is basically for to get the number of elements in array.but this code giving wrong output but when i apply this same logic in main method then i got right output but why. https://code.sololearn.com/c7g2KroSgcRs/?ref=app

2nd Oct 2019, 10:24 AM
Maninder $ingh
Maninder $ingh - avatar
6 Antworten
+ 3
Passing an array to a function decays it to a normal pointer that points to the first element of the array, so sizeof(arr) returns the size of an int*. It is still possible to index the array though, as arr[i] is just pointer arithmetic *(arr + i). Functions in C usually pass the size as an argument eg: snprintf, memcpy
2nd Oct 2019, 10:48 AM
jtrh
jtrh - avatar
+ 5
if i remember correctly in C when an array is passed as function parameter, only a pointer of the first element is being passed, not the entire array thus the sizeof giving a wrong size. i think using macro is the only way it could work.
2nd Oct 2019, 10:35 AM
Taste
Taste - avatar
+ 5
Since integer pointer which points to the first element of the array is passed. The size of integer pointer is 8 bytes and you're getting answer according to it.
4th Oct 2019, 9:37 AM
Manoj
Manoj - avatar
+ 4
The function j() receives an array parameter arr[] and tries to find out number of elements in arr[] using sizeof operator. In C, array parameters are treated as pointers. So the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int) which results in 2 for 64 bit machine (size of int is 4 and int * is 8).
2nd Oct 2019, 10:55 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 4
jtrh is possible to find the length of array in function or it is only possible in main method.
2nd Oct 2019, 11:01 AM
Maninder $ingh
Maninder $ingh - avatar
+ 3
Maninder $ingh it is always possible to find the length of an array, but you can't pass arrays to functions. Instead pass a pointer to the first element and the length of the array
2nd Oct 2019, 11:09 AM
jtrh
jtrh - avatar