0

What is the correct way to dynamically allocate memory.

int *arr = new int(5); or int *arr = new int[5]; i am confused...

2nd Jan 2021, 6:54 PM
Sp Maurya
Sp Maurya - avatar
8 ответов
+ 4
Both do it: int *arr = new int(5); Single int with a value of 5; int *arr = new int[5]; An array with room for 5 integers.
2nd Jan 2021, 7:29 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Thanks for sharing Sp Maurya ... I belive still [] is correct option.... C++ actually not checking size for array i.e. pointer arithmetic while iteration... This is what I feel and () is typo.... This is what I believe and not sure so waiting for others to respond.... My understanding in below code as code comment : https://code.sololearn.com/c4f5QhY68Vx6/?ref=app
2nd Jan 2021, 9:18 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
@Sp Maurya @Ketan Lalcheta goto:- https://www.bogotobogo.com/cplusplus/memoryallocation.php and scroll down to:- " Initializing Dynamically Allocated Objects" (it's about half-way down the page).
2nd Jan 2021, 10:03 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Could you please refer that link which suggests int(5) as 5 object? Wana go through it once for details it refers to
2nd Jan 2021, 8:30 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta https://www.guru99.com/cpp-dynamic-array.html#:~:text=It's%20easy%20to%20initialize%20a,be%20added%20to%20the%20array.
2nd Jan 2021, 8:56 PM
Sp Maurya
Sp Maurya - avatar
+ 1
Ketan Lalcheta yes you are absolutely right... [] this is the correct way but as you also see in your implementation... the same thing was confusing me... lets just consider it as a loop hole in c++ compiler for now... and wait for others to respond...
2nd Jan 2021, 9:37 PM
Sp Maurya
Sp Maurya - avatar
+ 1
Oh great rodwynnejones ... It means () is same as int constructor.... New int (5) means it points to some int value whose value is 5..... So, it solves my doubt that it is not array allocation but only a single element of array...
3rd Jan 2021, 1:58 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
rodwynnejones but on some sites i found that int *arr = new int(5); as an array with room for 5... that's why i am confused... and it works as well... but ya you are also right and i actually know that already...
2nd Jan 2021, 7:53 PM
Sp Maurya
Sp Maurya - avatar