Atul
Atul

Reputation: 765

A doubt about sizeof

I was trying to do something using sizeof operator in c++.
Please refer to the following code snippet.
http://ideone.com//HgGYB

#include <iostream>
using namespace std;
int main()
{
    int *pint = new int[5];
    int temp = sizeof(*pint);
    cout << "Size of the int array is " << temp << endl;
    return 0;
}

I was expecting the output as 5*4 = 20. Surprisingly it comes to 4. Any ideas ?

Upvotes: 2

Views: 250

Answers (7)

saurabh jindal
saurabh jindal

Reputation: 121

In the current case sizeof(*pint) is giving the sizeof(int), so its returning 4 . But, even if you will try sizeof(pint), it will return you the size of a pointer. Which will most probably be 4 if yours is a 32 bit machine else it will be 8, if 64 bit machine.

Now you have asked, why it is not returning 4*5 = 20. Since pint points to an integer array. Yes, pint points to an integer array, but its not an array. The difference is :

  1. Array have a fixed size. you can redectare it at all. While pointers can point to any object of any size.

Since sizeof operator is evaluated at compile time, so compiler dont have any way to know at which size of array this pointer is pointing and so cant tell the size of that object and so it always return only the size of pointer. now you can understand, why in case of pointers compiler gives size of the pointer (ie space occupied by pointer in memory), but in case of array it gives full size.

Upvotes: 0

iammilind
iammilind

Reputation: 69958

Here is pint is an int*. So,

sizeof(*pint) == sizeof(int)

Compiler doesn't know about new int[5], when it does sizeof(*pint) (because sizeof() is a compile time operator).

[Note: Try the same test with statically declared array, int pint[5]; and will see the expected result. Additionally, sizeof() returns size_t (which is an unsigned value), so it should be:

size_t temp = sizeof(...);

]

Upvotes: 6

James
James

Reputation: 66824

It is giving you the size of what the pointer points to - the first location in the array.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

There is no way for C++ to know the size of the array. In your case,

*pint

returns an int, and sizeof(int) is 4 on your machine.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

pint is a pointer to int that just happens to point to the beginning of an array. It contains no information about this array.

Upvotes: 0

murrekatt
murrekatt

Reputation: 6129

All fine. You ask for the size of an int which will be 4 bytes.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

Dynamically sized arrays lose their size information- the size is only the size of one integer, as pint is a pointer to int, and *pint is an integer, not an array type of any size.

Upvotes: 1

Related Questions