Miek
Miek

Reputation: 1137

Confusion about sizeof operator

I am using C++ on Mac OSX Lion and I have created the following code:

float* floatArray = new float[10];

for(int i = 0; i < 10; i++)
{
    floatArray[i] = 0.0 ;
}

std::cout<< "Test size of a float " << sizeof(floatArray[0]) << std::endl;
// The value is 4 byte which is what I would expect.

std::cout<< "Test the size of the whole array" << sizeof(floatArray) <<std::endl;
// the value is 8. I would have expected the value to be 40 bytes.

What am I not understanding?

Thanks in Advance

Upvotes: 1

Views: 224

Answers (5)

Coding Mash
Coding Mash

Reputation: 3346

In your system, size of the pointer in memory is 8 bytes. Sizeof() operator just looks at the size of that variable in memory. So it prints the size of the float pointer.

You can find more detail here. How to find the 'sizeof' (a pointer pointing to an array)?

Upvotes: 3

Useless
Useless

Reputation: 67852

Compare it with this (which actually is an array):

float floatArray[10] = {0.0};
std::cout<< "sizeof a float " << sizeof(floatArray[0]) << std::endl;
std::cout<< "sizeof the whole array " << sizeof(floatArray) << std::endl;

and then, if you need to use dynamically-sized or allocated arrays, consider using std::vector instead.

Upvotes: 2

user529758
user529758

Reputation:

The sizeof operator has no knowledge what and how many elements a pointer points to (except when you feed it an array, but that's not a pointer, again). So it returns sizeof (float *) - and as you're probably on 64-bit, the size of a pointer is 8 bytes long.

Upvotes: 0

Soturi
Soturi

Reputation: 1496

Your second sizeof(floatArray) is actually returning the size of the pointer, not the size of the array. See here

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409482

The expression sizeof(floatArray) returns the size of the pointer, not what it points to.

Upvotes: 7

Related Questions