1

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;
}
1
  • another ` scanf("%d%d", &rows, &cols); to replace with ` scanf("%d %d", &rows, &cols); ` ` Commented Feb 6, 2016 at 23:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.