Can anyone explain this code why it returning 8

#include <stdio.h> int foo(int a[100]){ return sizeof(a); } int main() { int a[10]; printf("%d", foo(a)); return 0; }

10/21/2019 9:27:56 AM


4 Answers

New Answer


Rachit Sharma It's a straight forward rule but first thing arrays and pointers are not same. Array decays to pointer when they are passed to the functions or when they are assigned to pointers e.g. assignment example int arr[10]; int *ptr = arr; // decay happens and ptr actually geys the address of first element i.e &arr[0] A 2D array like int arr[10][20] when passed to a function will decay to int (*ptr)[20] i.e looses it's row size information. int (*ptr)[20] != int *ptr[20] (this array of 20 pointers to int while the former is a pointer to an array of 20 ints. A 3D array int arr[2][3][5] decays to int (*ptr)[3][5]; I don't know what else to explain. Probably you may ask questions and i'll try to explain if i know :)


Preity When a N Dimension array is passed to a function it loose 1 dimension and decays to N-1 dimension. So the array you passed is decayed to a pointer, and sizeof(pointer) is usually 8 bytes on a 64 bit machine. This also happens when you assign an array to a pointer int arr[10]; int *ptr = arr; // decay happens and is actually &arr[0] i.e the address of first element That is why it is recommended to pass the size of the array as an explicit parameters.


~ swim ~ , Hatsy Rei anyone can explain this


~ swim ~ can you elaborate on that more please