【问题标题】:Passing 2 dimensional array to function将二维数组传递给函数
【发布时间】:2020-11-01 04:34:58
【问题描述】:

我正在尝试用 c 来做这件事

#include <stdio.h>
int getWordAmount(FILE *file);
void getWords(char names[][]);

int main() {
    FILE *file = fopen("files/country.txt", "a+");
    if(file != NULL) printf("File is opened\n");
    else printf("Error occured in opening file\n");
    int n = getWordAmount(file);
    char names[n][20];
    getWords(names);

    for(int i = 0; i < n; i++) {
        for(int j = 0; names[i][j] != '\0'; j++) {
            printf("%c", names[i][j]);
        }
    }
    return 0;
}

int getWordAmount(FILE *file) {
    char c;
    int charAmount = 0;
    while ((c = getc(file)) != EOF) {
        if((c == ' ')||(c == '\n')) charAmount++;
    }
    return charAmount;
}

void getWords(char names[][]) {
    int i = 0, j = 0, k = 0;
    char temp[20];
    while ((c = getc(file)) != EOF) {
        temp[i++] = c;
        if((c == ' ')||(c == '\n')) {
            i = 0;
            while((temp[i] != ' ')||temp[i] != '\n') {
                names[j][k++] = temp[i++];
            }
            j++;
            i = 0;
        }
    }
}

我收到如下所示的此错误

E:\Programming\C Files\files.c:3:20:错误:数组类型不完整 元素类型'char[]' 3 |无效getWords(字符名[][]); | ^~~ E:\Programming\C Files\files.c:3:20:注意:“名称”声明为 多维数组必须具有除 第一个 E:\Programming\C Files\files.c: 在函数'main'中: E:\Programming\C Files\files.c:11:12:错误:形式参数的类型 1 不完整 11 |获取单词(名称); | ^ E:\编程\C Files\files.c:在顶层:E:\Programming\C Files\files.c:30:20: 错误:数组类型的元素类型不完整 'char[]' 30 |空白 getWords(字符名称[][]){ | ^ E:\Programming\C 文件\files.c:30:20: 注意:将“名称”声明为多维数组必须具有 除第一个 E:\Programming\C 之外的所有维度的边界 Files\files.c:在函数“getWords”中:E:\Programming\C Files\files.c:33:11: error: 'c' undeclared (first use in this 功能) 33 |而 ((c = getc(file)) != EOF){ | ^ E:\编程\C Files\files.c:33:11:注意:仅报告每个未声明的标识符 每个函数出现一次,它出现在 E:\Programming\C Files\files.c:33:20: error: 'file' undeclared (first use in this 功能);您指的是 'fileno' 吗? 33 |而((c = getc(文件))!= EOF){ | ^~ |文件号

这是我的国家.txt

Bangladesh India China Nepal Bhutan
Pakistan Indonesia America Miyanmar
USA North-Korea South-korea Brazil
Argentina
Indonesia Japan Singapur Africa Rassia

【问题讨论】:

  • 您不能将形参声明为char names[][]。必须指定第二个维度(更准确地说,除了第一个之外的所有维度),否则它将无法索引到数组中。所以char names[][20] 可以工作(它会调整为char (*names)[20]),或者您可以使用可变尺寸。
  • 多维数组除了第一个维度外,所有维度都必须有边界。

标签: arrays c function pointers 2d


【解决方案1】:

正如您所看到的错误,多维数组的声明必须具有除第一个维度之外的所有维度的边界。 所以你可以这样做(其中一种方法和最简单的方法):

// in your case the 20 is second dimension
void getWords(char names[][20]) {
    int i = 0, j = 0, k = 0;
    char temp[20];
    while ((c = getc(file)) != EOF) {
        temp[i++] = c;
        if((c == ' ')||(c == '\n')) {
            i = 0;
            while((temp[i] != ' ')||temp[i] != '\n') {
                names[j][k++] = temp[i++];
            }
            j++;
            i = 0;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-10
    相关资源
    最近更新 更多