0

I need help with filling up a char array in c++ with a letter and without using a loop. This is what i have so far.

int n, m;
    cin >> n >> m;
    char canvas[n][m] = {{'B'}};

This however won't work. Does anyone know how I can do this?

  • 2
    Hint: `std::vector`. – tadman Feb 17 '21 at 21:38
  • @scohe001 Wouldn't loop take a long time? – Shadow_Walker Feb 17 '21 at 21:39
  • 1
    You are trying to create a VLA, which is not included in the C++ standard (but is available as an extension in some implementations) – Ted Lyngmo Feb 17 '21 at 21:39
  • 1
    Hint 2: VLAs like `char canvas[n][m]` are [not part of the C++ standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) and have a tendency of blowing up the stack. `std::vector` will solve both of your problems. – Lukas-T Feb 17 '21 at 21:39
  • ok i will try vector. thx!!! – Shadow_Walker Feb 17 '21 at 21:39
  • 1
    @Shadow_Walker If you're writing values to many different locations, somebody has to do the loop. All you can hope for is that somebody writes the loop better than you do. – user4581301 Feb 17 '21 at 21:40

1 Answers1

4

You can do this pretty easily with a 2D std::vector:

int n, m;
std::cin >> n >> m;
std::vector<std::vector<char>> canvas(n, std::vector<char>(m, 'B'));
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • 2
    Entry #9,582,108 in our ongoing series of "Why you should be using `std::vector`" – tadman Feb 17 '21 at 21:40
  • A 1D flat vector would be even better than a 2D sparse vector: `std::vector canvas(n*m, 'B');` Though, the code is dealing with `char`, so there is always `std::string` instead: `std::string canvas(n*m, 'B');` – Remy Lebeau Feb 17 '21 at 22:48