C - the number of elements in the array?

Suppose 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 go into numItems number of elements that are in the arr array?

+6
source share
7 answers

Sorry, you cannot get this. In C, the following 2 are equivalent declarations.

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

You must transfer the size yourself.

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

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

+11
source

Either you pass the number of elements in another argument, or you have some kind of convention on the separating element in the array.

+5
source

I originally suggested this:

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

But this will not work , since arr not defined in the current context and is interpreted as a simple pointer. Thus, in this case, you will need to specify the number of elements as a parameter . The proposed operator would otherwise work in the following context:

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

You can not. The number must be sent to MyFunction separately. So add the second argument to MyFunction, which should contain the size.

+2
source

As I said in the commentary, passing it as another argument seems to be just a solution. Otherwise, you may have a globally defined agreement.

+2
source

This is not possible if you do not have a predefined array format. Because potentially you can have any amount of float. And with const float arr[] you only pass the base address of the array to a function of type float [] , which cannot be changed. So you can do arr[n] for any n .

+1
source

better than

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

is an

 int numItems = sizeof(arr)/sizeof(*arr); 
+1
source

Source: https://habr.com/ru/post/893797/


All Articles