1

Possible Duplicate:
length of array in function argument

I am trying to get the length of an integer array but i am not getting the right answer

void main()
{
    int x[]={33,55,77};
    printf("%d",getLength(x));//outputs 1
    printf("%d",sizeof(x)/sizeof(int));//outputs 3
}

int getLength(int *inp)
{
    return sizeof(inp)/sizeof(int);
}

So why is getLength returning value 1 instead of 3 ?

Community
  • 1
  • 1

3 Answers3

3

Because arrays aren't pointers, and pointers aren't arrays. sizeof(pointer) is not the same as sizeof(the array which the pointer points to).

2

Since arrays decay to pointers, you cannot perform length calculation in a function: the function gets a pointer, not an array. You need to do the computations inline the way your function does when it prints 3, or use a macro to compute array length:

#define GET_LENGTH(inp) (sizeof(inp)/sizeof(*inp))

Here is a link to a demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

The sizeof(inp) here is returning the size of pointer and not the size of array and the size of pointer = 4

So

sizeof(inp)/sizeof(int)
 ^__ 4        ^__ 4      = 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268