开发者

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 re开发者_运维知识库turn...

    return 1

}

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


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


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


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
}


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.


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


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 .


better than

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

is

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜