Going off pure instinct, rather than testing this, the sizeof the static array (20) is convieniently a multiple of 5 - the records you declared when initialising the array, and 4 - the size of the *int_array from your first main() function.
The static array sizeof is giving the total size of the statically declared array. The sizeof the contents of the dynamic int_array is the size of what it points to, the head of the array.
This has peeked my interest, I'm going to have a little play. But my feeling is that, rather than being a difference in behaviour between static and dynamic arrays, its more a difference of how sizeof interprets what it has been given. so int intArray[5];
is not a pointer, its statically declared and using the data memory of the program. Its dimensions are known. Its an integer array, so its size is 4 bytes (for an int) * 5 (number of elements).
Whereas int *intArray{new int[10]};
is instanced with a new
, so its living on the heap. But it's a pointer, and we know that pointers just point to an area of memory. So sizeof just gives the block that the pointer is pointing to, which we know is the first element of a dynamically created array, its an integer so its 4 bytes.
Edit: continuing my musing... getting the size of the whole dynamic array, to mimic what happens with sizeof a static array, we can add all the elements together and expect to see the same answer doubled (since you declared the dynamic array as 10, not 5 as is the static array)
#include <iostream>
#define ARRAYSIZE 5
using namespace std;
int main()
{
int *int_array{ new int[5] };
cout << "Saying:\n";
cout<<sizeof(*int_array);
cout << "\nIs the same as saying:\n";
cout<<sizeof(int_array[0]);
cout<<"\n";
cout << "Mimic sizeof(static_array), we need to:\n";
int size = 0;
int i = 0;
for (i = 0; i < ARRAYSIZE - 1; i++) {
size+=sizeof(int_array[i]);
cout<<sizeof(int_array[i]);
cout<<" + ";
}
cout << sizeof(int_array[i+1]);
cout << " = ";
cout<<(size+=sizeof(int_array[i+1]));
cout << "\nwhich is the same size as the static sizeof!\n";
return 0;
}
And running, gives:
noscere@bertram:~/src/Stack/dynamicArrays$ g++ dynArray.cpp -o dynArray
noscere@bertram:~/src/Stack/dynamicArrays$ ./dynArray
Saying:
4
Is the same as saying:
4
Mimic sizeof(static_array), we need to:
4 + 4 + 4 + 4 + 4 = 20
which gives us the same size as the static sizeof!
Change ARRAYSIZE
to 10, as you originally declared, we get 40.