0

in void pa() sizeof array returns 2 whereas same line in main() returns 7 the actual size of the array why this is happening?

#include <stdio.h>
void pa(int arr[])
{
    int n = sizeof(arr) / sizeof(arr[0]);// here it give o/p as 2 but in main()
    for(int i=0;i<sizeof(arr)-1;i++)
    printf("%d \t",arr[i]);
    printf("\n %d \n",n);
    printf("end \n");

}
int main()
{
    int arr[]={5,8,3,6,7,2,4};
    printf("the array\n");
    int n = sizeof(arr) / sizeof(arr[0]);//here it return 7 but why
    printf("\n %d \n",n);
    pa(arr);
    return 0;
}

ks1322
  • 33,961
  • 14
  • 109
  • 164
x_skark
  • 19
  • 3
  • its not C# problem, so removed C# tag – Vivek Nuna Jan 21 '23 at 10:42
  • The function has no idea what the size of the array passed is (even if defined as say `int arr[7]`). The size must be passed as another argument, unless the array contains a 'sentinel' value (such as a C string has). – Weather Vane Jan 21 '23 at 10:51
  • 2
    x_skark, `arr` in `main()` is an array (an array of 7 `int`). `arr` in `pa()` is a pointer (A pointer to an `int`). Try printing just the size of `arr` in both functions. – chux - Reinstate Monica Jan 21 '23 at 11:43
  • 1
    Declaring an "array" in a formal argument list is a bit deceptive, since the compiler "adjust" the declaration to a pointer. In an argument list, `int a[]` becomes `int *a`, i.e. it's really a pointer, not an array, so `sizeof` gives the size of a pointer. – Tom Karzes Jan 21 '23 at 14:54

0 Answers0