0

What is the problem?

I'd written a program in C that can print out the number of the elements of an array. #include<stdio.h> int main(){ int num[] = {1, 2, 3, 4, 5}; printf("%d", sizeof(num) / sizeof(num[0])); return 0 } --> 5 However, when I turned it to function, it printed out a different result. What is the problem? Here's my function: #include<stdio.h> int length(int arr[]){ return sizeof(arr) / sizeof(arr[0]); } int main(){ int num[] = {1, 2, 3, 4, 5}; printf("d", length(num)); return 0; } --> 2

25th Aug 2020, 6:56 AM
Tha Rath Rbt
Tha Rath Rbt - avatar
5 Réponses
+ 2
When dealing with arrays, we usually set the array length as parameter : void doThings(int arr[], int arr_length) ;
25th Aug 2020, 7:23 AM
Théophile
Théophile - avatar
+ 6
int arr[] is an array pointer, whose size is, on a 64 bit system, 64 bits. An int is 32 bits wide (at least in your example). 64 / 32 = 2
25th Aug 2020, 7:00 AM
Théophile
Théophile - avatar
+ 2
There is no standard mechanism in C to determine array size at run time... sizeof only works on compile time... You could use some kind of termination character, as with strings, that marks the end of the array... But for sure, this this character must never occur in your data... There are some more creative ways to do it, but it will always be a compromise...
25th Aug 2020, 7:22 AM
G B
G B - avatar
+ 1
Use for loop to print array Numbers and u forget to use % in printf
25th Aug 2020, 7:34 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
So, what can I do to print the number of elements from the function?
25th Aug 2020, 7:08 AM
Tha Rath Rbt
Tha Rath Rbt - avatar