+ 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; }

14th Jan 2020, 5:10 AM
Ibrahim Kaiser Reza
Ibrahim Kaiser Reza - avatar
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; }
14th Jan 2020, 5:39 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 5
If 'a' is the size of your array then why don't you declare the array as- int li[a];
14th Jan 2020, 5:25 AM
Avinesh
Avinesh - avatar
0
Thanks Avinesh, but that is also showing error like this - " variable sized object may not be initialized"
14th Jan 2020, 5:32 AM
Ibrahim Kaiser Reza
Ibrahim Kaiser Reza - avatar