getting different answer for sizeof(arr) in different scenario?;

61 views Asked by At

consider these two programs:

//////////////////////Program 1////////////

void print(int arr[])
{
 int *p=arr;
 cout<< sizeof(arr)<<endl; //// here it is 8 
}

int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
print(arr);
return 0;
}

///////////////////////////// ///////////////////Program 2///////////

#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30};
printf("%ld \n",sizeof(arr)); /// here it is 12
return 0;
}

////////////

1

There are 1 answers

0
Bathsheba On BEST ANSWER

arr has decayed to a pointer type once it's been passed to print. So sizeof within that function yields the size of a pointer to int on your platform.

In Program 2, that decay has not occurred: the type of arr is an array of 3 ints. The size is sizeof(int) * 3.