簡體   English   中英

動態分配2D字符串數組

[英]Dynamically allocating a 2D string array

該代碼似乎在正確的軌道上,但是它跳過了一行,而忽略了第一個元素[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;
}

這條線

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

在輸入緩沖區中保留newline ,因為"%d"格式消耗前導空格,但不尾隨空格。 因此,當執行此行時

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

它讀取剩下的newline 您可以通過在"%c"前面添加一個空格來解決此問題

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

它會在您要讀取的char之前占用所有前導空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM