How to create an array of size n filled will 0s. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to create an array of size n filled will 0s.

How can I create an array of size n (user input) filled with 0s?

10th Sep 2022, 6:33 AM
ss7
4 Answers
+ 3
int arr[size]{}; use brace list initialisation it guarantees to initialize member with 0s
10th Sep 2022, 9:11 AM
Prashanth Kumar
Prashanth Kumar - avatar
+ 2
You can't. You need to allocate memory on the heap if you want to do that. You can use std::vector for that (it's basically an array but is allocated on the heap at runtime, and can grow and shrink in size) ``` size_t n; std::cin >> n; std::vector<int> arr((n)); ``` This will create a dynamic array `arr` of size n, filled with 0s EDIT: just to clarify, you CAN initialize an array with 0s as described by Prashanth Kumar if the size is known at compile-time. But if you want to initialize the array with a runtime variable, you need to do this.
10th Sep 2022, 10:33 AM
XXX
XXX - avatar
+ 1
wait..oops.. did he said its uses input 😅 sry..i thought he asked compile time fixed size array ...
10th Sep 2022, 10:46 AM
Prashanth Kumar
Prashanth Kumar - avatar
10th Sep 2022, 10:36 AM
Prashanth Kumar
Prashanth Kumar - avatar