2

i am taking a C pointer course on mycodeschool this is the code in C:

#include<stdio.h>
int SumOfElements(int A[])
{
    int i, sum = 0;
    int size = sizeof(A)/sizeof(A[0]);
    printf("SOE size of A = %d, size of A[0] = %d\n", 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("Main size of A = %d, size of A[0] = %d\n", sizeof(A), sizeof(A[0]));
    printf("Sum of elements = %d\n", total);
}

according to the output should be: enter image description here instead this code i got the output: enter image description here

according to the tutorial he explained that when the complier see an array as function argument it does not copy the whole array, it just creates a pointer variable instead of creating the whole array. so in this case the compiler just copy the address of the first element in the array of the calling function(which is the main function). so the size of A in mycodeschool's code is 4 which makes sense. but why my output of sizeof(A) is 8?

Danh Le
  • 95
  • 3
  • 10

1 Answers1

1

It's not strange at all, as you stated, the argument int A[] is in fact int *A, A decays to a pointer to the first element of the array when passed as an argument of a function.

So sizeof A is the size of a pointer to int. In 64 bit systems, the size of a pointer is usually 8 bytes in size, whereas in a 32 bit one is usually 4, this is not a rule but it's the usual behavior.

anastaciu
  • 23,467
  • 7
  • 28
  • 53