0

In this code snippet i passed array A in sumOfElements(A) function as it hold the reference of the first value of array A which is an integer, it's size should be 4. Instead it returning 8.

#include <iostream>
using namespace std;

int sumOfElements(int A[])
{
    int i, sum = 0;
    int size = (sizeof(A) / sizeof(A[0]));

    cout << "Size of A " << sizeof(A) << endl;
    cout << "Size of A[0] " << sizeof(A[0]) << endl;

    for (i = 0; i < size; i++)
    {
        sum += A[i];
    }

    return sum;
}

int main()
{
    // Arrays as function arguments

    int A[] = {1, 2, 3, 4, 5};
    int total = sumOfElements(A);

    // cout << "Sum of elements = " << total << endl;

    cout << "Size of A " << sizeof(A) << endl;
    cout << "Size of A[0] " << sizeof(A[0]) << endl;

    return 0;
}

Result

Size of A 8
Size of A[0] 4
Size of A 20
Size of A[0] 4

Expected result is

Size of A 4
Size of A[0] 4
Size of A 20
Size of A[0] 4
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Jabid Hasan
  • 19
  • 1
  • 7
  • 4
    A is a pointer which is 8=64 bit – Daniel A. White Nov 18 '22 at 04:37
  • 3
    In `sumOfElements`, `A` decays to a pointer, so `sizeof(A)` is `sizeof(int *)` which is unsurprisingly 8 bytes on a 64-bit system. – Nate Eldredge Nov 18 '22 at 04:37
  • Basically, a function can't use `sizeof` to determine the size of an array passed in by the parent. Arrays don't know their own sizes in C; the size is only known, by the compiler, within the block where the array was declared. You need to pass the length as a separate argument. – Nate Eldredge Nov 18 '22 at 04:38
  • Even if the array were passed as-is instead of decaying to a pointer, I'm not sure I understand why the expectation is 4 instead of the same 20 that you see in `main` given that you're using the same operator on the same array. – chris Nov 18 '22 at 05:09
  • I found the reason behind, the code is also giving the same result. In 32 bit architechture it gives 4 byte on the other hand in 64 bit architechture it gives 8 byte. Thanks Everyone. :) – Jabid Hasan Nov 18 '22 at 06:23

0 Answers0