Hi,
I want choice dynamic size for array, and user can enter arbitrary size of n.
Similar this.
What i do? I don't like use pointer or any advanced code.(I need solution for beginners)
Note: I am a beginner. (so my answer may not be correct)
It is not possible to have the user enter the size of an array without using a pointer/list type data structure. I am sure you will see an error if you try to compile saying something like "array cannot be initialized with a variable", and that is even if you have already initialized the variable BEFORE the array declaration.
I think it is something to do with how the program compiles. For every array defined, it allocates the necessary memory for it before moving to the next piece of code.
Addition: The only way I found around this in my earliest days was to simply create an array that is larger or as large as what could possibly be used. If this is a solution for beginners, there should be no harm in creating a large array, especially if the data is entered manually. Of course, you should probably tell the user the maximum size of the array and/or give a message only when more data than the allowable size is attempted.
#include <iostream>
#include <string>
#include <vector>
struct Test
{
std::string test;
}
std::vector<Test> global; //Creates an empty global vector of Test
int main()
{
int n;
std::cin >> n;
std::vector<Test> local(n); //Creates vector of n Test structs
global.resize(n); //global now stores n Test structs
//Vectors can be easily used just like arrays:
gobal[0] = "Hello";
local[0] = "world";
std::cout << global[0] << ", " << local[0] << '\n';
}