0

So I have been learning java this past year in school, but now I am trying to teach myself C++ and I am confused. I want to create an array of any size the user wants. But I cant do it the same way as in java and I want to know why and how can i do it in c++.

int main(){
int numOfCylinders = 1;
cout << "Welcome to the Cylinder Sorter!\n How many cylinders are we creating?\n";
cin >> numOfCylinders;

const int SIZE = numOfCylinders;

Cylinder cylinder[SIZE]; // First i tried making the size of the array equal to numOfCylinders but it 
                         // it said it needed to be a constant value. I then made a const int variable
                         // called SIZE and assigned its value equal to numOfCylinders hoping that it
                         // would be a work around to my current issue.
                         
while (true) {
    for (int i = 0; i < numOfCylinders; i++) {
        cout << "Enter the a character for Cylinder " << i;
        cin >> cylinder[i].setName();
    }
    //rest of code isnt written
}

}

If this doesnt make any sense im sorry...

Andriani
  • 1
  • 1
  • 2
    Arrays are only allowed to have a size that is known at compile-time in C++. Since input could be anything, the compiler cannot know the size. Assigning it to a `const int` will not make a difference, the size is still unknown. Use `std::vector` instead. – mediocrevegetable1 Apr 28 '21 at 05:40
  • https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – Retired Ninja Apr 28 '21 at 05:44
  • Because the size of an array is required to be a compile-time constant so that the compiler can set up all of the indexing math and perform other wizardry for you. Anything you get from the user is too late to be of use. Some compilers allow Variable Length Arrays as a non-Standard extension to make C++ look more like C99, but it's not required behaviour and often a source of undesirable behaviour. For example, what if the user input 4,000,000,000? A typical computer has between 1 and 10 MB storage allocated to Automatic storage, and I'm willing to bet 4 billion `Cylinder`s exceeds that. – user4581301 Apr 28 '21 at 05:44
  • @mediocrevegetable1 ahh okay thank you! – Andriani Apr 28 '21 at 05:44
  • @user4581301 This makes sense, but i guess u could also just have a check if the user input a size that was too large it would ask for another size that is below or equal to a certain amount. Thank you for the response! – Andriani Apr 28 '21 at 05:45
  • 1
    As you say you're teaching yourself C++ then embrace the use of `std::vector` over raw arrays. – acraig5075 Apr 28 '21 at 06:08

0 Answers0