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;

}
4

1 回答 1

0

功能:read_line()返回新的行号。但是该main()函数忽略了返回值,因此不更新局部变量row_num,因此代码块以:

while (row_num > 0)

永远不会被执行

read_line()不需要第二个参数。该参数可能只是函数中的局部变量而不是参数

于 2019-03-03T17:13:50.197 回答