+ 2
What's wrong with this code? Showing "segmentation error"
#include<iostream> using namespace std; int main() { int a,b; cin >> a; int li[] = {}; for(int i = 0; i<a; i++){ cin >> b; li[i] = b; } for(int i = 0;i<a;i++){ cout << li[i] << " "; } return 0; }
4 odpowiedzi
+ 7
The way you are declaring array, you need to create dynamic array as you are taking the size of array by user input.
And at last, you need to free the memory allocated on the heap.
int main()
{
int a,b;
cin >> a;
int *li = new int[a];
for(int i = 0; i<a; i++) {
cin >> b;
li[i] = b;
}
for(int i = 0;i<a;i++){
cout << li[i] << " ";
}
delete[] li;
return 0;
}
+ 5
If 'a' is the size of your array then why don't you declare the array as-
int li[a];
0
Thanks Avinesh, but that is also showing error like this - " variable sized object may not be initialized"