How can I get arrayLength from user defined function?
int getArrayLength(int *arr){
//our logic
return result;
}
How can I get arrayLength from user defined function?
int getArrayLength(int *arr){
//our logic
return result;
}
Simply: you cannot. You should pass it as another argument:
int getArrayLength(int *arr, int size){ ...
If you try with sizeof, it will return the size of the pointer. You can also use a special value to indicate the last element of your array (like 0 for strings), but adding a convention can make things more complicated.
You'll need to do one of two things:
Have the caller provide the length, or...
Agree on a sentinel value that lets you detect the end of the array.
In the general case, the right answer is option 1. You shouldn't write functions that take C arrays without also taking a length parameter.
In some specific cases, option 2 works pretty well. For example, \0
is used to mark the end of strings, which are just character arrays. If 0
isn't a valid value for the elements of array, that could work for cases other than strings. But generally, go with option 1.
Pass array length to the function too otherwise you can't. This is because sizeof(arr)
will give you size of the pointer to int
, not the size of entire array.