I am trying to take 2 dimensional char data from user, but it’s not taking input from user properly. Could you highlight the bug in following code?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i, j, k;
char **ch;
printf("\nEnter k : ");
scanf("%d",&k);
ch = (char **) malloc (sizeof(char*) * k );
if(ch == NULL) { printf("\n Not enough memory for ch array "); exit(0);}
for(i = 0; i < k; i++) {
ch[i] = (char *) malloc (sizeof(char) * k );
if(ch[i] == NULL) { printf("\n Not enough memory for ch array "); exit(0);}
}
printf("\nenter char matrix ( %d X %d )\n", k,k);
for(i = 0; i < k; i++) {
for(j = 0; j < k; j++) {
scanf("%c", (*(ch + i) + j) );
}
}
printf("\n char matrix : \n");
for(i = 0; i < k; i++) {
for(j = 0; j < k; j++) {
printf("%c ",*(*(ch + i) + j));
}
printf("\n");
}
for(i = 0; i < k; i++) free(*(ch + i));
free(ch);
return 0;
}
I tried replacing char by int. It does work fine for integers.
What’s wrong with char reading from stdin?
Problem:
after
scanf("%d",&k);there’s still a newline in the input buffer, that becomes the first entry of thecharmatrix. If you enter further newlines while filling the matrix, they become matrix entries too.Clear the input buffer before filling the matrix.