6

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?

user3262424
  • 7,223
  • 16
  • 54
  • 84
  • 1
    I remember that I used to make size as another argument for such kind of functions.. – mihsathe Jul 28 '11 at 16:56
  • 3
    possible duplicate of [Number of elements in static array and dynamic array](http://stackoverflow.com/questions/2577711/number-of-elements-in-static-array-and-dynamic-array) – sth Jul 28 '11 at 17:07

7 Answers7

11

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'.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
5

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

Prof. Falken
  • 24,226
  • 19
  • 100
  • 173
5

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
}
Ioan Paul Pirau
  • 2,733
  • 2
  • 23
  • 26
2

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.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
2

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

mihsathe
  • 8,904
  • 12
  • 38
  • 54
1

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 .

phoxis
  • 60,131
  • 14
  • 81
  • 117
1

better than

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

is

int numItems = sizeof(arr)/sizeof(*arr);
user411313
  • 3,930
  • 19
  • 16