i want to create a dynamic matix to enter a character , so i start firstly with creating a dynamic matric of int to after switch it to char the code of the dynamic matrix works correctly :`
#include <stdio.h>
#include <stdlib.h>
int main(){
int r , c , b;
int *ptr, count = 0, i;
printf("ROWS ");
scanf("%d",&r);
printf("COLS ");
scanf("%d",&c);
ptr = (int *)malloc((r * c) * sizeof(int));
for (i = 0; i < r * c; i )
{
scanf("%d",&b);
ptr[i] = b;
}
for (i = 0; i < r * c; i )
{
printf("%d ", ptr[i]);
if ((i 1) % c == 0)
{
printf("\n");
}
}
return 0;}
but when i did this change to switch it to matrix of char it doesn't read all the charecter so it stopped reading before the matrix finish
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r , c ;
int count = 0, i;
char *ptr,b;
printf("ROWS ");
scanf("%d",&r);
printf("COLS ");
scanf("%d",&c);
ptr = (char *)malloc((r * c) * sizeof(char));
for (i = 0; i < r * c; i )
{
scanf("%c",&b);
ptr[i] = b;
}
for (i = 0; i < r * c; i )
{
printf("%c ", ptr[i]);
if ((i 1) % c == 0)
{
printf("\n");
}
}
return 0;
}
CodePudding user response:
It seems you need to write
scanf(" %c",&b);
^^^^
to skip white space characters including the new line character '\n'
that corresponds to the pressed Enter key.
That is when the format string starts from the space character white space characters are skipped.
Pay attention to that you should free the allocated memory when the dynamically allocated array is not needed any more.
Otherwise if you want to read also spaces in the array then you can rewrite the for loop the following way
for (i = 0; i < r * c; i )
{
do scanf("%c",&b); while ( b == '\n' );
ptr[i] = b;
}