Morgan Ariel Henry
Morgan Ariel Henry

Reputation: 39

Dynamically allocating a 2D string array

The code seems to be on the right track however it skips out on a row and disregards the first element [0,0] pushing everything completely back by an element.

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


int main()
{
  char **nums;
  int i,j,k, num_cases;
  int rows, cols;

  printf("Enter the number of grids.\n");
  scanf("%d", &num_cases);


  for(k=0;k<num_cases;k++){
    printf("Test Case #%d\n", k+1);
    printf("Enter the # of rows & columns separated by a space.\n");
    scanf("%d%d", &rows, &cols);

    nums = (char**)malloc(rows*sizeof(char*));

    for(i=0; i<rows; i++){
      nums[i] = (char*)malloc(cols*sizeof(char));
    }

    printf("Enter your %dx%d grid of letters.\n", rows, cols);
    for(i=0; i<rows; i++){
      for(j=0; j<cols; j++){
        scanf("%c", &nums[i][j]);
      }
    }
  }

  for(i=0; i<rows; i++){
    for(j=0; j<cols; j++){
      printf("[%d][%d] = %c\n", i, j, nums[i][j]);
    }
  }

  for(i=0; i<rows; i++){
    free(nums[i]);
  }

  free(nums);
  return 0;
}

Upvotes: 1

Views: 71

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

This line

scanf("%d%d", &rows, &cols);

is leaving a newline in the input buffer, because "%d" format consumes leading whitespace but not trailing whitespace. So when this line is executed

scanf("%c", &nums[i][j]);

It reads the newline that was left. You can deal with this by adding a space in front of the "%c" like this

scanf(" %c", &nums[i][j]);

which will consume any leading whitespace before the char you want to read.

Upvotes: 1

Related Questions