Why the array size is 1 [duplicate]

限于喜欢 提交于 2019-12-20 04:09:11

问题


Possible Duplicate:
Sizeof an array in the C programming language?

I'm trying to write a function that return 1s if a value is in the array. Here's the code:

int inArrayInt(int iVal, int iArray[])
{
    int i;
    int arrayL = sizeof(*iArray) / sizeof(int);
    int flag = 0;
    for(i=0; i < arrayL; i++)
    {
        if(iVal == iArray[i])
        {
            flag = 1;
        }
    }
    return flag;
}

The problem is that arrayL = sizeof(*iArray) / sizeof(int); always evaluates to 1, even if array contains 20 elements. Why?


回答1:


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++){
    ...
  }
}



回答2:


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?)




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/11224204/why-the-array-size-is-1

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