Reputation: 2183
Have a look at following code
void fun( int *p )
{
// is there any solution to calculate size of array as we are not explicitly passing its size.
}
void main ()
{
int a[5];
fun (a);
}
Is there any solution to calculate size of array in function or explicitly passing its size is the only solution?
Upvotes: 2
Views: 85
Reputation: 9680
When you pass an array to a function, the array is implicitly converted to a pointer to its first element. Thus what you are actually passing is a pointer to the first element of the array, not the array itself. In fact, you can't pass to or return an array from a function. They are not first class objects in C
. Hence, you must pass the length of the array to the function as well.
void fun(int *p, int len) {
// function body
}
int main(void) {
int a[5];
fun(a, 5);
}
Upvotes: 3
Reputation: 50657
You cannot.
It's just one pointer, which contains no size info of the array. That's why it's a common implementation to pass the size of the array as a second parameter to the function.
Upvotes: 3
Reputation: 280301
The pointer p
contains no data about the size of the array. You don't quite have to pass the size as a parameter - you could end the array with a 0
like strings do, or hardcode the length, or do any of a number of other things - but without some sort of additional machinery, you can't get the length from just a pointer.
Upvotes: 3