Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C -- number of elements in an array?

Tags:

c

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?

like image 931
user3262424 Avatar asked Jul 28 '11 16:07

user3262424


People also ask

How do you find the size of an array in C?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

How we can get the number of elements in an array?

We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array.

How do you determine the number of elements in an array String s a/b/c };?

The simple method to find the number of objects in an array is to take the size of the array divided by the size of one of its elements. Use the sizeof operator which returns the object's size in bytes.


2 Answers

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

like image 102
Armen Tsirunyan Avatar answered Sep 24 '22 13:09

Armen Tsirunyan


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

like image 27
Nobody moving away from SE Avatar answered Sep 25 '22 13:09

Nobody moving away from SE