-1

sizeof(Array_Name) when used in side main function is returning the number of bytes of this array, while when it is used inside a userdefined function it retures the size of the pointer (and this is because it is passed to the function as a pointer).

My question is that, why when sizeof(Array_Name) is used inside main, it is not treated as a pointer?

Sameh NAGI
  • 43
  • 2
  • 7

2 Answers2

0

This is because array names decay into pointers when passed to functions. For example

int main()
{
    int arr[3] = { 1, 2, 3 };
    printf("main: %zu\n", sizeof(arr));

    f(arr);
}
void f(int *ptr)
{
    printf("%zu", sizeof(ptr));
}

Output:

main: 3 * sizeof(int)
f: sizeof(int *)

(Where sizeof... is replaced with the actual value on your compiler)

Also, it doesnt depend on whether the array is declared in main or not. This rule is more general: In the function where the array is declared, it is treated as an actual array. Only when it is passed as an argument to a function, is it converted into a pointer to the first element. This is why functions taking arrays take a pointer to the first element, and a size argument.

void print(const int *arr, size_t n)
{
    size_t i;

    for (i = 0; i < n; ++i)
        printf("%d\n", arr[i];
}
lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
0

I have a feeling, you have something like char Array_Name[20]; which would return '20' from the function you declared it in, but then you pass it into another function, which accepts: void f(char *Array_Name) {...} and here the value printed is 4 or 8 (size of char *). To make this easier to understand, first rename the argument in the function to void f(char *My_Pointer) {...}. Now realize that 'sizeof' is resolved at compile time, not run-time. There fore, at compile time, all we know is that My_Pointer points to a character array, but could be called with various arrays, so it really makes a lot of sense to evaluate to size of (char *).

Alex
  • 1,192
  • 14
  • 30