'2D char array issues with input and output

I'm having a bit of trouble with this homework problem. We are basically making a "labyrinth" populated by characters. However, I'm not sure how to even get started because I have issues with creating the 2D char array. Here is my current code:

char** read_labyrinth  (int* rows, int* cols)
{ 
    cin >> *rows >> *cols;

   char **labyrinth = NULL;
   labyrinth = new char*[(*rows)]

   for (int i = 0; i < (*rows); i++)
   {
         labyrinth[i] = new char[(*cols)];
   }

   for (int i = 0; i < (*rows); i++)

   {
       cin >> labyrinth[i];   
   }

  return labyrinth;
}

I also have this to print the labyrinth, but nothing is ever printed out. The program is started be doing something like ./labyrinth > labyrinth1.in where the text file has two numbers for rows and cols as well as a bunch of characters like #* to populate, but nothing has ever been outputted for me. If anything, rows and cols seem to get set with garbage values, so I figure I must be doing something terribly wrong. Here is the print function

void print_labyrinth (char** maze, int rows, int cols)
{
     for (int i = 0; i < rows; i++)
      {
            cout << maze[i];
      }

}

Thank you for any help. I'm quite lost.



Solution 1:[1]

This basic sample worked for me :

#include <iostream>
using namespace std;

char** read_labyrinth  (int rows, int cols)
{ 

   char **labyrinth = NULL;
   labyrinth = new char*[rows];

   for (int i = 0; i < rows; i++)  {
         labyrinth[i] = new char[cols];
   }

   for (int i = 0; i < rows; i++)   {
    for (int j = 0; j < cols; j++)
      {
          cin >> labyrinth[i][j];   
      }
   }
  return labyrinth;
}
void print_labyrinth (char** maze, int rows, int cols)
{
    cout << "labyrinth is : \n";
     for (int i = 0; i < rows; i++)
      {
        for (int j = 0; j < cols; j++){
                cout << maze[i][j];
            }
               cout<<"\n";
      }    
}
int main() 
{
    int r, c;
    cout << "enter no of rows and columns \n";
    cin >> r >> c;
    print_labyrinth(read_labyrinth(r,c),r,c);
    return 0;
}

Online editor link ideone - link

You do need too take care to free the memory still.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s