Using sizeOf, Pointers explanation

I've been working my way slowly through on understanding pointers. One of the examples in the book shows how to use getSize to return the number of bytes in an array. When I looked at the function I figured rather than doing it in a function I could just add the * into sizeOf thinking that it should return the same result. But it returned 8 rather than 4, so I'm a bit confused on why it returned a different value. I was wondering what it actually returned and why it returned a different value?

Snippets of code:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
   double dArray[ 20 ];
   cout << "The number of bytes in the array is " << sizeof (dArray );
   cout << "\nThe number of bytes returned by getSize is " << getSize( dArray );
   cout << "\ntesting here: " << sizeof( *dArray ) << endl;
}

size_t getSize( double *ptr )
{
   return sizeof( ptr );
}


The program's output is:
The number of bytes in the array is 160
The number of bytes returned by getSize is 4
testing here: 8
Your getSize function should return sizeof( *ptr ); not return sizeof( ptr );

If you do so, you will see that it is size_t 8. This is because the size of the actual element is 8 (what the pointer points to)

4 is the size of the pointer itself, not the value of the pointee, which is a value of type double.

Your top result of 160 is the size of the memory address of the array, which means 8 * 20 = 160

The difference is sizeof (dArray) returns the size of an array[double] not a double*.

Although in most cases pointer arithmetic and array notation are similar and sometimes interchangeable, this is not one of those times.


Make sense?
Last edited on
Okay, I think I do now. I just had to reread it a few times and think it through in my head. Thanks.
Topic archived. No new replies allowed.