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?

0

4 Answers 4

7

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

1
  • 3
    As a sidenote, the OP has commited another error by doing sizeof(*iArray).
    – Eitan T
    Jun 27, 2012 at 10:39
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++){
    ...
  }
}
2
  • 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, 2012 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, 2012 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.

0
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.