c - How to use fgets() in 2d-arrays (multiple dimension arrays)? -
#include <stdio.h> #include <stdlib.h> void *salloc(int x){ char **pointer; int i; pointer = malloc(sizeof(char)*x); if(pointer == null){ exit(-1); } for(i=0; i<x; i++){ pointer[i] = malloc(sizeof(char) * 20); if(pointer[i] == null){ exit(-1); } } return pointer; } void input(int value, char **array){ for(i = 0; < value; i++){ printf("%d ----\n", i); fgets(array[i], 20, stdin); printf("%d ----\n", i); } } int main(int argc, char *argv[]){ char **array; int value = 2; array = salloc(value); input(value, array); return 0; }
the general idea, can miss syntax. want read in string spaces. if run value 2, print:
0 ----
0 ----
1 ----
"some string"
and crashes after press enter. if value 1: crashes. if replace fgets() with:
scanf("%s", array[i]);
it works (except spaces).
so how fgets() work in 2d-arrays?
because work in 1d-arrays. , reason can print 1d-arrays row 2 when array has 2 rows, should able print rows 0 , 1 right?
here demonstrative program shows how fgets
can used 2d array.
#include <stdio.h> #define n 5 #define m 10 int main( void ) { char lines[n][m]; size_t n = 0; while( n < n && fgets( lines[n], sizeof( *lines ), stdin ) != null ) ++n; ( size_t = 0; < n; i++ ) puts( lines[i] ); return 0; }
if enter example
one 2 3 4 5
then program output same
one 2 3 4 5
Comments
Post a Comment