+ 1

Numbers in freshly declared arrays, what do they mean?

Can somebody please explain the difference in initializing the arrays between the presented two ways and why the initial readings don't always equal to 0 after declaring an array? The readings in the second array actually change from launch to launch. https://sololearn.com/compiler-playground/cpbzDYYkvVTA/?ref=app

9th Feb 2024, 8:38 PM
Tabs Morgan
Tabs Morgan - avatar
4 Respuestas
+ 4
They are both unitialized. It just happens that the first one got 0's. you can write int *p = new int[size](); int arr[size]{}; to create 0 initialized array also, the second way is better because you have to free up every new call... delete[] p; p = nullptr; to avoid memory leaks and prevent access .
10th Feb 2024, 12:18 AM
Bob_Li
Bob_Li - avatar
+ 1
Wow, two curly brackets is all it takes to fix. Thank you, that's super compact!
10th Feb 2024, 12:24 AM
Tabs Morgan
Tabs Morgan - avatar
+ 1
They are both unitialized. It just happens that the first one got 0's. you can write int *p = new int[size](); int arr[size]{}; to create 0 initialized array also, the second way is better because you have to free up every new call... delete[] p; p = nullptr; to avoid memory leaks and prevent access .
12th Feb 2024, 1:01 PM
Nirmit
Nirmit - avatar
+ 1
Nirmit I posted that, and so... what is it that you want to add to this? just curious about the copy-paste post.
12th Feb 2024, 2:30 PM
Bob_Li
Bob_Li - avatar