I tried to ask int num forever. But didn't work.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i ;
for (int j=0; j<i; j ) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY When I enter the 3rd value it gives a strange reaction
CodePudding user response:
int MyArray[]={};
Now, MyArray
has a size of 0
, so any indexes that you tried to access MyArray
will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector
in the <vector>
header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i ;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j ) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std;
is bad, so don't use it.
CodePudding user response:
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.