Search code examples
carraysmazeansi-c

function not printing correctly in c


I am trying to build a dynamic maze i got to the part where i get the size and get the chars that i need to build the maze from them. but the function thats build the maze prints it really asymmetrical how can i fix that?

my code:

  #include <stdio.h>
  #include <stdlib.h>

 char **board;
 int size = 0;

 void print_Board();
 void initialize_Board();

int main()
{
  initialize_Board();
  print_Board();

 return 0;
}

/*initialize the board*/
void initialize_Board()
 {
    int i, j;//indexs
    char s;
    scanf("%d", &size);

 board = (char**)malloc(sizeof(char*)* (size)); 
 if (!board) { printf("ERROR - memroy allocation.\n"); exit(1); }

 for (i = 0; i < size; i++)//for loops to build the board for the game
 {
    board[i] = (char*)malloc(sizeof(char)*(size));                              
   if (!board[i]) { printf("ERROR - memroy allocation, for loop\n");  
      exit(1); 
    }

    for (j = 0; j < size; j++)
    {
        scanf("%c", &s);
        board[i][j] = s;
    }//for col

    printf("\n");

  }//for row
}

//print the board
void print_Board()
  {
    int i, j;

for (i = 0; i < size; i++)
  {
        for (j = 0; j < size; j++)
        {
        printf("%c ", board[i][j]); //print the value in the [i][j] place.
        }//for col

        printf("\n");

       }//for row
 }

Solution

  • Change:

    for (j = 0; j < size; j++)
    {
        scanf("%c", &s);
        board[i][j] = s;
    }//for col
    

    To:

    for (j = 0; j < size; j++) {
        scanf("%c ", &s);
        board[i][j] = s;
    }//for col
    board[i][j] = '\n'; // Add new line to end of row making it a string.
    

    This ensures that each character is read and the return char is discarded.

    and change:

    int i, j;
    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            printf("%c ", board[i][j]); //print the value in the [i][j] place.
        }//for col
    
        printf("\n");
    
    }//for row
    

    to:

    int i;
    
    for (i = 0; i < size; i++) {
        printf("%s", board[i]); //print the values in the [i] row.
    }
    

    This prints each row with a newline at the end.