Can I? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can I?

Can I name my array like this: cin >> n; int a[n]; ???

26th Sep 2018, 6:57 AM
Daniil Mishkin
Daniil Mishkin - avatar
3 Answers
+ 4
No. The size of a static array is supposed to be known at compile time.
26th Sep 2018, 7:03 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar
+ 4
Nguyễn Văn Hoàng I think we can but yes we cannot change its size. Run this code and it's working fine. #include <iostream> using namespace std; int main() { int num = 0; cin >> num; int arr[num] = {0}; for(int i = 0; i < num; i++) { arr[i] = i; cout << arr[i] << " "; } return 0; } [Edited]: You are correct, I was confused. This code will run on SoloLearn without any errors because it take inputs before runtime but on other compilers it will give error
26th Sep 2018, 5:28 PM
blACk sh4d0w
blACk sh4d0w - avatar
0
I think what you ask for is dynamic memory allocation for an array which size is not known at compile time. c++ provides functionality for such cases. Have a look at this code: https://code.sololearn.com/ciL7c2xy4CLb/?ref=app
26th Sep 2018, 7:27 PM
mimtelf
mimtelf - avatar