user3262424
user3262424

Reputation: 7479

C -- number of elements in an array?

Suppose that I have the following c function:

int MyFunction( const float arr[] )
{
    // define a variable to hold the number of items in 'arr'
    int numItems = ...;

    // do something here, then return...

    return 1

}

How can I get into numItems the number of items that are in the array arr?

Upvotes: 6

Views: 5758

Answers (7)

user411313
user411313

Reputation: 3990

better than

int numItems = sizeof(arr)/sizeof(float);

is

int numItems = sizeof(arr)/sizeof(*arr);

Upvotes: 1

Ioan Paul Pirau
Ioan Paul Pirau

Reputation: 2833

I initially suggested this:

 int numItems = sizeof(arr)/sizeof(float);

But it will not work since arr is not defined in the current context and it's being interpreted as a simple pointer. So in this case, you will have to give the number of elements as parameter. The suggested statement would otherwise work in the following context:

int MyFunction()
{
     float arr[10];
     int numItems = sizeof(arr)/sizeof(float);
     return numItems;// returns 10
}

Upvotes: 5

mihsathe
mihsathe

Reputation: 9154

As I said in the comment, passing it as another argument seems to be only solution. Otherwise you can have a globally defined convention.

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132974

Unfortunately you can't get it. In C, the following 2 are equivalent declarations.

int MyFunction( const float arr[] );
int MyFunction( const float* arr );

You must pass the size on your own.

int MyFunction( const float* arr, int nSize );

In case of char pointers designating strings the length of the char array is determined by delimiter '\0'.

Upvotes: 11

Either you pass the number of elements in another argument or you have some convention on a delimiting element in the array.

Upvotes: 5

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

You can't. The number will have to be passed to MyFunction separately. So add a second argument to MyFunction which should contain the size.

Upvotes: 2

phoxis
phoxis

Reputation: 61910

This is not possible unless you have some predetermined format of the array. Because potentially you can have any number of float. And with the const float arr[] you only pass the array's base address to the function of type float [] which cannot be modified. So you can do arr[n] for any n .

Upvotes: 1

Related Questions