I want to ask how a pointer helps a user to input array. I thought constant variables were required to declare an array... Programming Language is C++ .
2 Answers
C++ is not an IDE, you probably have an IDE that uses a C++ compiler.
Constant variables are NOT needed to declare an array, constant variables are used to declare something that will not be changed.
Arrays are defined by the size, so I suppose that's what you mean by constant. However, the fields in the array are changeable (thus not constant).
To answer your question, using an array is frowned upon when getting input, as you have no idea what the user will input and the size is suppose to be constant.
My suggestion is to use a std::vector as a container to hold and store an ever-expanding collection of data
Here's some more information about arrays, and declaring them / getting input:
Example of a constant array:
const std::string days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
Example of a non-constant array:
std::string days[5];
Example of getting input from user (and putting it inside the first position of the array (0)):
std::cin >> days[0];
Example of non-constant array using a pointer (this is an array, as it's using the new keyword):
std::string *days;
days = new std::string[5];
Example of using a std::vector (better choice for storing data, that will not be constant in size):
std::vector<std::string> days;
days.push_back("Monday");
Comments
If you define a raw C-like array allocated on the stack, like:
int arr[10];
then the element count (in this case 10) must be known at compile-time.
If you still want a raw C-like array, but with size based on some user's input (which happens at run-time), then you can use new[]:
int count; // Elment count
cin >> count; // Read from user
assert(count > 0); // Check validity
// Create raw array on the heap at run-time.
// Use a *pointer* to store the address of the beginning of the array.
int* arr = new int[count];
... work with the array ...
// Cleanup the array
delete[] arr;
Note that in modern C++, it's better to just use std::vector. In this case, you don't need pointers, and dynamic memory allocation (as well as cleanup) happens under the hood of std::vector:
// count read from user input.
// Vector of integers allocated at run-time.
std::vector<int> arr(count);
// ... work with vector ...
// No need to manual cleanup: thank you C++, destructors and RAII.
std::vectoris better.