Sameh NAGI Sameh NAGI - 3 months ago 8
C Question

sizeof(Array_Name) inside main function VS sizeof(Array_Name) inside a user defined function

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?

Answer

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];
}
Comments