+ 1

Need help regarding arrays

# include <stdio.h> void print(int arr[]) { int n = sizeof(arr)/sizeof(arr[0]); int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; print(arr); return 0; } on executing it.. output is 1,2 why??

4th Mar 2018, 3:28 PM
Ayush walia
Ayush walia - avatar
5 Antworten
+ 1
Hi, everyone... thanks for answering... but my question was not how to fix this program, but instead why is it printing 1,2.. Either way if anyone else wants to know.. the answer.. so after searching through web i figured out... [] is used to make it clear that the function expects an array, it doesn’t change anything though. People use it only for readability so that the reader is clear about the intended parameter type. The bottom line is, sizeof should never be used for array parameters, a separate parameter for array size (or length) should be passed to print(). So, in the given program, n contains ration of pointer size and integer size, this ration= is compiler dependent. since pointer size is either 4 or 8 bytes and int is 2 or 4 bytes.. n becomes 2... so thats why 1,2 prints...
6th Mar 2018, 2:01 PM
Ayush walia
Ayush walia - avatar
+ 5
I updated program so it works. Size of an array is only valid, where the compiler can figure out the allocated space. The only thing passed into a function is an address of where the array starts in memory so it is impossible there. https://code.sololearn.com/cl9Psq6LK9Y7
4th Mar 2018, 7:31 PM
John Wells
John Wells - avatar
+ 4
pass n into print. There isn't anyway the print code can tell the size of arr as it isn't part of the data passed in with the array.
4th Mar 2018, 4:00 PM
John Wells
John Wells - avatar
+ 2
Try putting sizeof(int) instead of sizeof(arr[0])
4th Mar 2018, 5:17 PM
Rugved Modak
Rugved Modak - avatar
0
i've looked at this code and i think it's because you have to give to the function calling the array also its size so that operation to calculate its size (n) should be in the main function. to mistake the function does it's: array has 8 numbers inside the main function calls the print function which needs the array it should calculate the size (n) by using the number of bytes of the array divided by the number of bytes of a cell so ( 4(bytes of int) * 8)/4 that's where it fails and thinks is 8/4 = 2 so 0 and 1 i have no experience with c ... so i don't know how to calculate it in the function but i suggest you to calculate it in main and call the function void Print(int array[],int n)
4th Mar 2018, 4:03 PM
Alessio Bocini
Alessio Bocini - avatar