1

I want to declare an array[x], but I want my array's size changeable for every each new programm start. My first idea was int x; scanf("%d",&x); one line before I declare my array[x] but that doesent work because x have to be a const int.

My next idea was simply make a const int x; scanf("%d", &x); but this try also failed, because array[x] or rather say the const int x must be initialized before I can start the programm.

My last idea was to initialized the x const int x = 1; and on the next time scanf("%d", &x); In this try the programm didnt crashed, but it wasnt usefull. In the moment if I start the programm my array[x] got initialized with my "old" x. So my changed x have no impact.

Do u have any ideas how I can solve this little problem or this there no way to initialize a const int or overall a const type after I start the programm in C++?

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Erik
  • 33
  • 3
  • Read in the `x`. Output source code using that `x` value that does what you want. Compile that generated code. Run the program from the generated code. Alternatively, use `std::vector`. – Eljay Jul 07 '21 at 14:58
  • 1
    It seems like what you want is a constant expression, which is not something you can get at run time. If the purpose is to use it as an array dimension, you could just use `std::vector`. – cigien Jul 07 '21 at 14:58

1 Answers1

2

Unfortunately you can't do this directly. What you can do is to use this idea:

const int x = []{int x; scanf("%d", &x); return x;}();

For an array,

const std::vector<double> v = []{
 int x; scanf("%d", &x);
 std::vector<double> v(x);
 ...fill v...
 return v;
}();

If you want an array that is fixed in size (after initialization) but with modifiable elements, you have to look even beyond to a static_vector kind of structure. (This variation of array is not a nice type to work with anyway).

alfC
  • 14,261
  • 4
  • 67
  • 118