Problem entering numbers into an array

I am trying to make a program that asks for the size of an array, prompts the user to enter numbers into the array, and finally displays the numbers back to the user. When I use this code with more than 4 numbers I get this output

OUTPUT

Enter array size: 5

Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Number 1: 1
Number 2: 2
Number 3: 3
Number 4: 4
Number 5: -559823264
Program ended with exit code: 0





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <iostream>
using namespace std;

int main(){
    int arraysize, inputindex, arrayin, arrayout;
    int array[arraysize];
    
    //prompts user to enter size of the array
    cout << "Enter array size: ";
    cin >> arraysize;
    cout << endl;
    
    // user enters number in each slot of the array
    for (inputindex=0; inputindex < arraysize; ++inputindex) {
        cout << "Enter number " << inputindex+1 << ": ";
        cin >> arrayin;
        array[inputindex]=arrayin;
        
    }
    
    //displays numbers in array
    for (arrayout=0; arrayout < arraysize; ++arrayout) {
        cout << "Number " << arrayout+1 << ": "<< array[arrayout] << endl;
    }
    
}
Last edited on
Your code is not valid C++.

1
2
int arraysize, inputindex, arrayin, arrayout;
int array[arraysize];


How big do you think array is? Hint: arraysize is an uninitialized variable (garbage).

In standards compliant C++, array dimensions must be known at compile time.

BTW, you're missing a
[/code]
tag.

Ok, thank you. So is it not possible to create an array with a variable that the user can enter as the size?
Only using dynamic memory.
1
2
3
4
  int *array;
  array = new int [arraysize];
//  Do something with array 
  delete [] array;


Dynamic memory is not recommended for beginners. std::vector is preferred.
Last edited on
Vector or smart pointers:

1
2
3
4
5
6
#include <memory>

  auto array = std::make_unique<int[]>( arraysize );
  // Do something with array

  // std::unique_ptr does deletion 


1
2
3
4
5
6
#include <vector>

  std::vector<int> array( arraysize );
  // Do something with array

  // std::vector does deletion 

Thank you! I used vectors and it works now.
Topic archived. No new replies allowed.