In function Sum why is program returning an 8 in sizeof(A) instead of 4? Int*P points to first element in array A which is an integer of 4 bytes.
Thanks.
#include <iostream>
using namespace ::std;
int Sum(int* A, int size)
{
int sum = 0;
cout << "In Sum size of A = " << sizeof(A) << " and size of A[0] = " << sizeof(A[0]) << endl;
for (int i = 0; i < size; i++)
{
sum+= A[i];
}
return sum;
}
int main()
{
int A[] = {2,4,5,6,7};
int size = sizeof(A) / sizeof(A[0]);
int total = Sum( A, size);
cout << "In Main size of A = " << sizeof(A) << " and size of A[0] = " << sizeof(A[0]) << endl;
cout << "Sum of elements = " << total << endl;
}
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
What compiler are you using? A 64 bit compiler will return 8 for the size of an int.
Int*P points to first element in array A which is an integer of 4 bytes.
The size of what P points to is irrelevant. What matters is the size of the pointer itself. It sounds like you're using a 64 bit compiler, so pointers (all pointers) are 8 bytes.
In Sum(), A is a memory pointer. The size of a pointer is 8 for 64bit compile and 4 for 32bit - irrespective as to the type to which the pointer points.
Note that with a memory pointer sizeof() returns the size of the pointer - NOT the amount of memory. So sizeof(A) in main is probably 20 (5 elements of 4 bytes) with sizeof(A[0}) probably 4.
But when A is passed to sum(), the array A is degraded to a pointer. From a pointer you can't determine how many elements (or bytes) are used. Hence you need to also pass size (the number of elements).
#include <iostream>
#include <span>
#include <numeric>
auto Sum(std::span<constint> A) {
std::cout << "In Sum A has " << std::size(A) << " elements\n";
return std::accumulate(A.begin(), A.end(), 0LL);
}
int main() {
constint A[] { 2, 4, 5, 6, 7 };
std::cout << "In main A has " << std::size(A) << " elements\n";
constauto s { Sum(A) };
std::cout << "Sum of elements = " << s << '\n';
}
which displays:
In main A has 5 elements
In Sum A has 5 elements
Sum of elements = 24
#include <numeric>
template < std::size_t N > longlong Sum( constint (&A)[N] )
{
std::cout << "In Sum A has " << N << " elements\n";
return std::accumulate( A, A+N, 0LL );
}
Edit: long long came with C++11, so the return type would have to be long in C++98. Which is less than ideal.
For typical values, std::ptrdiff_t can be used as signed std::size_t.
For char arrays shorter than PTRDIFF_MAX, std::ptrdiff_t acts as the signed counterpart of std::size_t:
it can store the size of the array of any type. https://en.cppreference.com/w/cpp/types/ptrdiff_t