简体   繁体   English

将多维char数组传递给C中的void函数时出错

[英]Error when passing multidimensional char array to a void function in C

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. 我将多维数组传递给函数“ read_line”,但返回的只是一维数组,请参见下面的代码。 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? “ read_line”的作用是读取句子并将每个单词保存为2D数组中的单个字符串,但是当我尝试在主函数中打印2D数组时,我只有1D数组,为什么? 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;

}

the function: read_line() returns the new row number. 函数: read_line()返回新的行号。 But the main() function is ignoring the returned value, so not updating the local variable row_num so the code block beginning with: 但是main()函数忽略返回的值,因此不更新局部变量row_num因此代码块以以下内容开头:

while (row_num > 0)

will never be executed 永远不会被执行

the second parameter to read_line() is not needed. read_line()的第二个参数。 That parameter could simply be a local variable in the function rather than a parameter 该参数可以只是函数中的局部变量,而不是参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM