1

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?

Community
  • 1
  • 1
Antonio Ciccia
  • 696
  • 3
  • 8
  • 18

4 Answers4

6

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

Community
  • 1
  • 1
panickal
  • 1,114
  • 9
  • 13
2

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++){
    ...
  }
}
RedX
  • 13,656
  • 1
  • 46
  • 69
  • He is actually doing `int arrayL=sizeof(int)/sizeof(int);`, there are two bugs in the code and you only address one. – Lundin Jun 27 '12 at 11:09
  • @Lundin `sizeof(*iArray)` is not per se wrong. And applying the fix as a described will remove that error source. – RedX Jun 27 '12 at 11:46
1

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.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
1

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
ThomasCle
  • 6,592
  • 7
  • 38
  • 78