Help to find error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Help to find error

#include <iostream> #include<conio.h> using namespace std; int main() { int myArr[y]; for(int x=0; x<y; x++) { cin>>myArr[y] ; cout << x << ": " << myArr[x] << endl; } return 0; }

21st Dec 2018, 4:02 PM
Aryan Verma
Aryan Verma - avatar
8 Answers
+ 9
Try to give the array size prior ,outside of loop.. Nd cin >>myArr[x] as the number will be stored in that x place (0,1,2 etc) int main() { int y; cin>>y; int myArr[y]; for(int x=0; x<y; x++) { cin>>myArr[x] ; cout << x << ": " << myArr[x] << endl; } return 0; }
21st Dec 2018, 4:18 PM
Frost
Frost - avatar
+ 7
#include <iostream> using namespace std; int main() { const int y = 3; int myArr[y]; for(int x = 0; x < y; x++) { cout << "input " << x+1 << ": "; cin >> myArr[x]; cout << myArr[x] << endl; } return 0; } Sample output: input 1: 5 input 2: 7 input 3: 1
21st Dec 2018, 4:19 PM
Babak
Babak - avatar
+ 6
Frost cin >> y; int myArr[y]; The above statement (int myArr[y];) needs to be replaced with dynamic allocation as int *myArr = new int[y]; //... delete[] myArr;
21st Dec 2018, 4:21 PM
Babak
Babak - avatar
+ 6
C++ Soldier (Babak) is it a mandatory thing to do , or just for flexibility of memory allocation ? cz my code should work too 🤔
21st Dec 2018, 4:32 PM
Frost
Frost - avatar
+ 6
Ohhh i see.. Thanx for the useful info ... C++ Soldier (Babak) Mohit the coder (M.S.D)
21st Dec 2018, 4:43 PM
Frost
Frost - avatar
+ 5
If the size of the array has to be determined during runtime, it's mandatory because the compiler is required to ask the OS to set aside a heap block for the cause. Also, the compiler issues an error like "expression 'y' must have a constant value".
21st Dec 2018, 4:40 PM
Babak
Babak - avatar
+ 3
A note about VLA (Variable-Length Array) in C++: Even though, the Frost's code is a valid construct in C99 — and gets compiled and run on SL — but, VLAs are not part of C++ standard. ____ https://en.wikipedia.org/wiki/Variable-length_array#C99 A good discussion: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard
21st Dec 2018, 5:50 PM
Babak
Babak - avatar
0
Frost If you are not allocating dynamic memory thenthere is slight chance of garbage value assign to the array
21st Dec 2018, 4:38 PM
MsJ
MsJ - avatar