0

I'm passing a multidimensional array to the function "read_line" but what I'm getting back is only 1D-array, see the code below. What "read_line" do is read the sentence and save every word as an single string in the 2D-array, but when I try to print the 2D-array back in the main function I got only 1D-array, why? Thank you a lot for the help

#include<stdio.h>
#include<string.h>

#define ROW 10
#define COLUMN 10


static char terminating_char;

int read_line(char array_string[ROW][COLUMN], int row_num);


int main() {

    int row_num=0;
    char array_string[ROW][COLUMN];

    printf("Write a sentens: ");
    read_line(array_string, row_num);

    printf("Reversal of sentence: ");
    while (row_num > 0)
        printf("%s ", array_string[row_num--]);
    printf("%s%c\n", array_string[row_num], terminating_char);

}

int read_line(char array_string[][COLUMN], int row_num) {

    char c;
    int i=0, j=0;

    while  ( (c = getchar())  != '\n' && i < ROW)
    {
        if (c == ' ' || c == '\t') {
            array_string[i][j] = '\0';
            i++;
            j = 0;
            continue;
        }

        if (c == '.' || c == '!' || c == '?') {
            terminating_char = c;
            array_string[i][j] = '\0';
            break;
        }
        else if (j < COLUMN)
            array_string[i][j++] = c;

    }
    return row_num;

}
SaifSa
  • 15
  • 5
  • 1
    Aside: function `read_line` does not use `row_num` passed to it, it works with row `i`. And in `main` since `row_num` is 0, the 2-D array is not used apart from the first row. The `while` loop does nothing, since `row_num` is 0. – Weather Vane Mar 03 '19 at 16:34
  • OT:The function `getchar()` returns an `int` , not a `char` – user3629249 Mar 03 '19 at 16:50
  • in function: `read_line()` what happens when a row begins with a space or a tab? – user3629249 Mar 03 '19 at 16:59
  • @user3629249 It'll be an empty string and will go to the next row. – SaifSa Mar 03 '19 at 17:03
  • the function: `read_line()` will lose characters when a word is more than 9 characters – user3629249 Mar 03 '19 at 17:07
  • the function: `read_line()` can/ input multiple lines. Each line can have its' own `terminating char` However, the posted code is only keeping the terminating character from the last row read – user3629249 Mar 03 '19 at 17:19

1 Answers1

0

the function: read_line() returns the new row number. But the main() function is ignoring the returned value, so not updating the local variable row_num so the code block beginning with:

while (row_num > 0)

will never be executed

the second parameter to read_line() is not needed. That parameter could simply be a local variable in the function rather than a parameter

user3629249
  • 16,402
  • 1
  • 16
  • 17
  • Thank you user3629249, the code is working for me now after adjustment on the while (row_num>0) – SaifSa Mar 03 '19 at 17:53