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
5 Answers
+ 2
When dealing with arrays, we usually set the array length as parameter :
void doThings(int arr[], int arr_length) ;
+ 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
+ 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...
+ 1
Use for loop to print array Numbers and u forget to use % in printf
0
So, what can I do to print the number of elements from the function?