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]; ???
3 Answers
+ 4
No. The size of a static array is supposed to be known at compile time.
+ 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
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