42

Possible Duplicate:
Sizeof an array in the C programming language?
Why does a C-Array have a wrong sizeof() value when it's passed to a function?

See the below code and suggest me that what is the difference of "sizeof" keyword when I used like this:

#include<stdio.h>
#include<conio.h>
void show(int ar[]);
void main()
{
    int arr[]={1,2,3,4,5};
    clrscr();
    printf("Length: %d\n",sizeof(arr));
    printf("Length: %d\n",sizeof(arr)/sizeof(int));
    show(arr);
    getch();
}
void show(int ar[])
{
   printf("Length: %d", sizeof(ar));
   printf("Length: %d", sizeof(ar)/sizeof(int));
}

But the output is like this:

Output is:

Length: 10

Length: 5

Length: 2

Length: 1

why I am getting like this; If I want to take the entire data from one array to another array the how can I do?

Suggest me If anyone knows.

Community
  • 1
  • 1
alishaik786
  • 3,696
  • 2
  • 17
  • 25

3 Answers3

64

Arrays decay to pointers in function calls. It's not possible to compute the size of an array which is only represented as a pointer in any way, including using sizeof.

You must add an explicit argument:

void show(int *data, size_t count);

In the call, you can use sizeof to compute the number of elements, for actual arrays:

int arr[] = { 1,2,3,4,5 };

show(arr, sizeof arr / sizeof *arr);

Note that sizeof gives you the size in units of char, which is why the division by what is essentially sizeof (int) is needed, or you'd get a way too high value.

Also note, as a point of interest and cleanliness, that sizeof is not a function. The parentheses are only needed when the argument is a type name, since the argument then is a cast-like expression (e.g. sizeof (int)). You can often get away without naming actual types, by doing sizeof on data instead.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 2
    show(arr, sizeof arr / sizeof *arr); – Soran Sep 05 '14 at 18:21
  • While I think this is the best general solution - i.e. pass the length and the array - I think it is also worth noting that for static arrays (i.e. length doesn't change during program execution) the simplest solution is to set the array size in the source code with a #define preprocessor definition. E.g. #define ARRAY_SIZE 5 – Bill May 31 '15 at 20:42
4

Thats the reason why, when writing a function that takes an array, two parameters are declared. one that is a pointer to the array, the other that defines the size of the array.

Julien May
  • 2,011
  • 15
  • 18
1

show() takes the address of the array which is stored on 2 bytes. Think of it as int *ar.

CoolStraw
  • 5,282
  • 8
  • 42
  • 64