0

I am a new programmer and I am trying to set up my code so that when I input the values for rows and columns that I want my 2D array to have, I continue to run into this error:

error C2131: expression did not evaluate to a constant note: failure was caused by a read of a variable outside its lifetime

What I have so far is simple:

    string cmd;
    int R, C;
    in >> cmd
    while( !in.fail() )
    { 
      if( cmd = "rows" )
      {
        in >> R;
      }
      if( cmd = "columns" )
      {
        in >> C;
      }
      in >> cmd;
    }
    char array[R][C];

When set up correctly, all the array[R][C] in my code will set the array to the [R][C] value from input similarly to how one would set the array to array[3][3] and such.

I am not sure how I should set this up so that my compiler understands I am trying to set my value set as constants, I appreciate any help. Thank you.

I am not allowed to use pointers or class/struct.

J. Doe
  • 3
  • 3
  • 1
    C++ doesn't have variable-length arrays. Use `std::vector>` – Barmar Oct 23 '17 at 21:14
  • Or since the size doesn't change after it's created, you could use `std::array`. – Barmar Oct 23 '17 at 21:17
  • And for completeness here is how you can implement it using `vector` https://stackoverflow.com/questions/1833127/two-dimensional-array-using-vector-in-cpp – Cory Kramer Oct 23 '17 at 21:20
  • I am unfamiliar with the use of vector arrays and unsure about how I could apply std::array to my code. The size does not change after it is created and the same size will be used throughout the duration of the run, so perhaps std::array would be what I would use. – J. Doe Oct 23 '17 at 21:22
  • Also, I am not allowed to use pointers or class/struct for my assignment – J. Doe Oct 23 '17 at 21:23
  • Then you need to talk to your instructor and get a clarification. What has been requested is not possible in standard C++. Your instructor may be under the mistaken belief that `char array[R][C];` is valid because they primarily use a compiler that has an extension that allows [variable length arrays](https://en.wikipedia.org/wiki/Variable-length_array). If they do not believe you, ask them to compile with the -pedantic flag on the command line. – user4581301 Oct 23 '17 at 21:42

0 Answers0