简体   繁体   English

动态分配2D字符串数组

[英]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. 该代码似乎在正确的轨道上,但是它跳过了一行,而忽略了第一个元素[0,0],将所有内容完全推回了一个元素。

#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;
}

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. 在输入缓冲区中保留newline ,因为"%d"格式消耗前导空格,但不尾随空格。 So when this line is executed 因此,当执行此行时

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

It reads the newline that was left. 它读取剩下的newline You can deal with this by adding a space in front of the "%c" like this 您可以通过在"%c"前面添加一个空格来解决此问题

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

which will consume any leading whitespace before the char you want to read. 它会在您要读取的char之前占用所有前导空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM