Why the array size is 1 [duplicate]

匆匆过客 提交于 2019-12-02 07:11:48

As a parameter int iArray[] is equivalent to int *iArray.

So when you do

int arrayL=sizeof(*iArray)/sizeof(int);

You are actually doing

int arrayL=sizeof(int)/sizeof(int);

Which is the same size.

You need to add a parameter with which you pass the size information.

int inArrayInt(int iVal, int iArray[], size_t numel){
  ...
  for(i=0;i<numel;i++){
    ...
  }
}
panickal

Because array decays to a pointer when you pass it into a function as an argument. And so the sizeof(array) will not give you the size of the array, but the size of the pointer.

You can either have the array size as an extra argument, or pass the array as a reference so that sizeof(array) will give you the correct size. (Detailed here: What is array decaying?)

What you pass to the function is a pointer to the array, with no way to know the size. The size of a pointer is the size of an int, hence the 1.

You need to pass the size of the array along with it in the arguments of your function if you want to iterate on it.

I'd add an extra parameter with the array size:

int inArrayInt(int iVal, int* iArray, int sizeOfArray)
{
    int i;

    for(i = 0; i < sizeOfArray; i++)
    {
        if(iVal == iArray[i])
        {
            return 1;
        }
    }

   return 0;
}

Then call the function with the size you initiated the array with:

int myArray[100];  


if (inArrayInt(42, myArray, 100))
   //returned true
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!