2

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?

1
  • 2
    Explicitly passing the size is the only solution. Commented Feb 22, 2014 at 9:45

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good idea to use a sentinel, +1 from me.
3

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.

Comments

3

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.