-2

I have this test program and it gives below output.

#include<iostream>
#include<cstdio>
void fun(char arr[])
{
printf(".size of char : %d\n.", sizeof(arr[0]));
printf(".size of char array: %d\n.", sizeof(arr));
}

main()
{
char arr[10]={'a','b','c','d','e'};
fun(arr);

printf("size of char array: %d\n", sizeof(arr));
}

output

.size of char : 1 ..size of char array: 8 .size of char array: 10

Now I understand that in first statement its size of member of array and in third statement is size of entire array but what does 8 in second printf says here?

devnull
  • 118,548
  • 33
  • 236
  • 227
anonymous
  • 1,920
  • 2
  • 20
  • 30

3 Answers3

6

Passing the name of array decays to pointer to its first element. So sizeof is returning size of pointer which is 8 on your host system.

Dayal rai
  • 6,548
  • 22
  • 29
3

When you pass an "array" to a function, you actually pass a pointer to the array. In other words, the expression sizeof(array) in fun returns the size of a pointer.

A common question in C and C++ is if you can find out the size of an array, given a pointer to it. Unfortunately, you can't.

Lindydancer
  • 25,428
  • 4
  • 49
  • 68
0

You are returning the size of the pointer of the array, and not the array. When you pass an array to a function, the compiler maps the memory of the pointer to your array and passes it to the function. The array isn't passed. This returns the size "8".

kotAPI
  • 1,073
  • 2
  • 13
  • 37