+ 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; }
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;
}
+ 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
+ 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;
+ 6
C++ Soldier (Babak) is it a mandatory thing to do , or just for flexibility of memory allocation ?
cz my code should work too đ€
+ 6
Ohhh i see..
Thanx for the useful info ... C++ Soldier (Babak) Mohit the coder (M.S.D)
+ 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".
+ 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
0
Frost If you are not allocating dynamic memory thenthere is slight chance of garbage value assign to the array