1

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

I have been working on this for long, but can't seem to understand why this is happening.

void fun(char []);

void fun(char a[])

{

   printf("Size is %d\n",sizeof(a));

}

int main ()

{

  char arr[10] = { 0 };

  printf("Size is %d\n",sizeof(arr));

  fun(arr);  

  return 0;

}

Why is the Output:

Size is 10

Size is 4

Community
  • 1
  • 1
Expert Novice
  • 1,943
  • 4
  • 22
  • 47
  • 1
    Exact duplicate: http://stackoverflow.com/questions/1975128/sizeof-an-array-in-the-c-programming-language – razlebe Mar 30 '11 at 10:51

3 Answers3

5

The first sizeof reports the size of a pointer, the second the size of an array.

A parameter declared with array syntax (void fun(char [])) is actually a pointer parameter. The [] is just syntactic sugar.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
5

It's because arrays when passed in functions get decayed into pointers in functions.

sizeof in fun() returns the size of the pointer a. Read about Arrays and Pointers.

a in fun() is actually a pointer copied by value.

You should pass the size of the array with as a separate argument.

You should try it this way:

#include <stdio.h>
void fun(char []);
void fun(char a[], int n)
{
//     printf("Size is %d\n",sizeof(arr));
       printf("Size is %d\n",n);
}
int main ()
{
  char arr[10] = { 0 };
  const int truesize = sizeof(arr)/sizeof(arr[0]); // try to understand this statement what it does -  sizeof returns size in bytes
  printf("Size is %d\n",truesize);
  fun(arr,truesize);  // This is how you should call fun
  return 0;
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Sadique
  • 22,572
  • 7
  • 65
  • 91
0

sizeof is an operator, it computes it value at compile time. sizeof(char[]) is the size of the pointer.

unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62