0

This program is about finding size of integer array and its elements size ,printing the size of array a[] in function void print_size(int a[]) ,it is showing sizeof(a) as 8 whereas in int main()function sizeof(a) is 12. How is the output for sizeof(a) function given in void print_size(int a[])is 8 but in int main() function sizeof(a) is 12 ,on running the program . Here is code given below:

 #include <stdio.h>
void print_size(int a[])
{
    printf("%d %d ",sizeof(a),sizeof(a[3]));
}
int main()
{
   int a[]={1,2,3};
   printf("%d %d \n",sizeof(a),sizeof(a[-1]));
   print_size(a);
   return 0;
 }  
  • 1
    Arrays decay to pointers when passed to functions. – user3386109 Aug 01 '20 at 17:47
  • Passing results of `sizeof` (its type is `size_t`) to `%d` (requires `int`) invokes *undefined behavior*. The correct format specifier is `%zu`. – MikeCAT Aug 01 '20 at 17:49
  • and since you're on a 64 bit machine, that's a size of 8 bytes for the 64 bit address – erik258 Aug 01 '20 at 17:51
  • If your thinking is that when you pass `a` to `print_size`, the size of the array is passed, you are expecting something that is literally impossible. Imagine if some other function that calls `print_size` only receives an `int *`. How could `print_size` possibly know what the "right" size is? – David Schwartz Aug 01 '20 at 17:58

0 Answers0