Home > other >  Why does my A[] function argument have size 8 bytes instead of 4?
Why does my A[] function argument have size 8 bytes instead of 4?

Time:03-01

I'm learning about C Pointer from freeCodeCamp.org and I'm getting stuck at the Array pointer as the function arguments follow by this.

In the instructor code was like this

int SumOfElement(int A[]) {
    int i, sum = 0;
    int size = sizeof(A)/sizeof(A[0]);
    printf("SOE - Size of A = %d, size of A[0] = %d", sizeof(A), sizeof(A[0]));
    for(i = 0; i<size; i  )
    { sum  = A[i];}
    return sum;
}

int main() {
    int A[]= {1,2,3,4,5};
    int total = SumOfElements(A);
    printf("Sum of elements %d\n",total);
    printf("Main - Size of A = %d, size of A[0] %d",sizeof(A),sizeof(A[0]));
}

And his result (from interested part) is :

SOE - Size of A = 4
Main - Size of A = 20

I understood why's that. But in my code when I try to run similar code I got 8 from printing sizeof(A) inside function

int myFunc(int a[]) {
    printf("Size of a[] inside function is %d\n", sizeof(a));
    return a;
}

int main(){
    int a[] = {1, 2, 3, 4, 5};
    myFunc(a); // Result is 8
    printf("Size of a[] in main function is %d\n", sizeof(a)); // Result is 20
    return 0;
}

CodePudding user response:

int A[] is an array declaration, but since it is part of a function parameter list, it gets implicitly adjusted into a pointer to the first element of that array.

int SumOfElement(int A[]) is 100% equivalent to int SumOfElement(int* A).

Therefore it is senseless to do sizeof A inside that function, because doing so will always give you the size of the pointer. Which is typically 4 bytes on a 32 bit system but 8 bytes on a 64 bit system.

For the same reason, int size = sizeof(A)/sizeof(A[0]); is nonsense. You can't calculate an array size like that when A is an array which has decayed into a pointer. This gives you the size of a pointer divided with the size of an int.

For this function to make sense, it should probably have a separate size parameter.

  • Related