c - Dynamically allocating a 2D string array -
the code seems on right track skips out on row , disregards first element [0,0] pushing element.
#include <stdio.h> #include <stdlib.h> int main() { char **nums; int i,j,k, num_cases; int rows, cols; printf("enter number of grids.\n"); scanf("%d", &num_cases); for(k=0;k<num_cases;k++){ printf("test case #%d\n", k+1); printf("enter # of rows & columns separated 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 %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 newline in input buffer, because "%d" format consumes leading whitespace not trailing whitespace. when line executed
scanf("%c", &nums[i][j]); it reads newline left. can deal adding space in front of "%c" this
scanf(" %c", &nums[i][j]); which consume leading whitespace before char want read.
Comments
Post a Comment