unexpected behaviour - sizeof(array).. pls explain..

int array[5];
cout << sizeof(array) // prints 5*sizeof(int) onto the console

but…

int *array = new int[5];
cout << sizeof(array) // prints the same constant number always irrespective of what I enter in
the brackets … int[ any size ]

What is exactly happening here??? pls somebody help

I figured out this strange behaviour while i was trying to sort a dynamic array using std::sort
std::sort(array, array+sizeof(array)/sizeof(array[0]));

1 Like

@bugkiller , @bit_cracker007… any idea…

1 Like

sizeof(a)…returns the memory that has been allocated to the variable ‘a’ in bytes.

for:-

int array[5];

memory allocated to array is 20 and hence 20 is the output!!!

but for:-

int *array;

memory allocated to array is 4 and hence 4 is the output!!

hope this helps…:slight_smile:

3 Likes

Hello,

“int *array = new int[5]; cout << sizeof(array) // prints the same constant number always irrespective of what I enter in
the brackets … int[ any size ]”

This is due to the notation you are using to declare a variable length array, which is correct.

However, keep in mind that sizeof(), returns the size, in bytes, of the argument it receives.

Now, as by declaring an array as int* array, you are in reality, saying that array is a pointer to the 1st element of the array, the output of sizeof() won’t change, regardless of the size you allocate.

Best regards,

Bruno

4 Likes

thank you very much for your clarification and patience reading my question…

2 Likes

thank you very much for your clarification and patience reading my question…

2 Likes

No need to thank you sir, it’s what we are all here for :slight_smile: If you find this answer to be the correct one, you can accept it as such so the topic can be closed :slight_smile:

1 Like

no need to thank dude…we are here to help as well as to ask for it…hope the ans cleared your doubt…:slight_smile:

2 Likes