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

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.