1

I am trying to fill an array with different integers, but it doesn't work as expected.

#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://i.stack.imgur.com/NhCsE.jpg

When I enter the 3rd value it gives an unexpected result.

Weston McNamara
  • 386
  • 5
  • 13
  • 2
    This declaration int MyArray[]={}; is invalid and does not make a sense. The number of elements in the array is unspecified. – Vlad from Moscow Nov 03 '21 at 12:42
  • Even if `int MyArray[]={};` was valid arrays are a fixed size at compile time and will never grow. Use a `std::vector` instead. Your code should be more like this example: [https://stackoverflow.com/questions/29312047/input-values-into-a-vector-until-the-end-of-input](https://stackoverflow.com/questions/29312047/input-values-into-a-vector-until-the-end-of-input) – drescherjm Nov 03 '21 at 12:50

2 Answers2

5
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.

1

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.