I'm creating a console timetable application in which you can create a timetable, change it, and delete it. I'm on the stage of taking the input for the calculator. However, when I run the code, as soon as I finish taking the input, the window just closes. Here is the code:
int input()
{
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};
for (int i = 1; i <= numberOfElements; i++)
{
cout << "Please enter a session: ";
cin >> itemArray[i];
}
for (int i = 0; i < numberOfElements; i++)
{
cout << itemArray[i] << "\n";
}
return 0;
}
There is some code in the main function as well, but it's irrelevant (only to find out for what day it is). I want you to have a look at the first for loop in the code, where I take in input. When running this code (in a separate window altogether), it closes as soon as I give in the input. Even if I say that I want 3 sessions (or any number), it closes right after I input the first session. In case you were wondering, I already tried replacing
char* itemArray[numberOfElements] = {};
with
char* itemArray[numberOfElements];
Just in case it's useful to anyone, I'm using the MinGW compiler.
Thanks.
std::vector<std::string>instead of messing withcharpointers and arrays like this.char* itemArray[numberOfElements]is not allowed in standard C++ since the size of arrays needs to be known at compile-time. It is allowed only as a compiler-specific extension. You would also need to allocate memory of sufficient size for each pointerchar*in the array manually, but please don't do that.cin >> itemArray[i];does not allocate memory to store the string and usingcin >>with achar*pointer is no longer allowed since C++20.for (int i = 1; i <= numberOfElements; i++)did you mean to start at 0 and go to< numberOfElements?cin >> numberOfElements; char* itemArray[numberOfElements] = {};is not standard C++.mainthat callsinputand exhibits the same behaviour you see in your program and a few include directives.