Search code examples
carraysmultidimensional-arrayfgets

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; i < 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 be that I miss some syntax. So I want to read in a string with spaces. If I run this for the value 2, it will print:

0 ----

0 ----

1 ----

"some string"

and it crashes after I press enter. If I do this with value 1: it immediately crashes. However if I replace fgets() with:

    scanf("%s", array[i]);

it works (except for the spaces).

So how does fgets() work in 2d-arrays?

Because I get it to work in 1d-arrays. And for some reason I can print 1d-arrays from row 2 when the array only has 2 rows, so it should only be able to print from rows 0 and 1 right?


Solution

  • Here is a demonstrative program that shows how fgets can be used with a 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;
    
        for ( size_t i = 0; i < n; i++ ) puts( lines[i] );
    
        return 0;
    }
    

    If to enter for example

    One
    Two
    Three
    Four
    Five
    

    then the program output will be the same

    One
    Two
    Three
    Four
    Five