c - 在 C 中返回二维数组…

标签 c arrays

我完全是 C 语言的菜鸟。我无法在这个函数和 main 之间建立连接。我正在尝试打印一个二维数组,但一直出现段错误。任何帮助将不胜感激。

编辑:当我将最后一行 'printf("%d:[%s]\n",i,*(p+i))' 从 %s 更改为 %c 时,我得到了我正在阅读的文件。结果是我的函数实际上返回了一些东西。现在只需要弄清楚如何让它从文件中的其他行返回单词。

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

#define num_strings 20
#define size_strings 20

int *read_file(){
    int j = 0;
    static char text[num_strings][size_strings];

    FILE *fp;
    int x;

    fp = fopen("dictionary2.txt", "r");

    char s[100];
    while(!feof(fp)) {
        x = fscanf(fp,"%[^\n]",s);
        fgetc(fp);

        if (x==1) {
            strcpy(text[j],s);
            j++;
        }
    }
    return text;
}

int main() {
    int *p;
    p = read_file();
    int i;
    for(i = 0; i < 10; i++) {
        printf("%d:[%s]\n",i,*(p+i));
    }
    return(0);
}

最佳答案

通常,您应该在main() 中创建您的数组并将其传入,这种行为是非常不正统的。然而,如果你坚持这样做,你必须返回一个指向你的数组的指针,因为你不能在 C 中返回数组。

这是你需要的东西:

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

#define num_strings 20
#define size_strings 20

typedef char (*PARR)[num_strings][size_strings];

PARR read_file(int * wordsread)
{
    static char text[num_strings][size_strings];
    FILE *fp;

    if ( (fp = fopen("dictionary2.txt", "r")) == NULL ) {
        fprintf(stderr, "Couldn't open file for reading\n");
        exit(EXIT_FAILURE);
    }

    char s[100];
    int j = 0;

    while ( j < num_strings && fgets(s, sizeof s, fp) ) {
        const size_t sl = strlen(s);
        if ( s[sl - 1] == '\n' ) {
            s[sl - 1] = 0;
        }

        if ( (strlen(s) + 1) > size_strings ) {
            fprintf(stderr, "String [%s] too long!\n", s);
            exit(EXIT_FAILURE);
        }

        strcpy(text[j++], s);
    }

    fclose(fp);
    *wordsread = j;
    return &text;
}

int main(void)
{
    int wordsread = 0;
    PARR p = read_file(&wordsread);

    for ( int i = 0; i < wordsread; ++i ) {
        printf("%d:[%s]\n", i, (*p)[i]);
    }

    return 0;
}

使用合适的输入文件,输出:

paul@horus:~/src/sandbox$ ./twoarr
0:[these]
1:[are]
2:[some]
3:[words]
4:[and]
5:[here]
6:[are]
7:[some]
8:[more]
9:[the]
10:[total]
11:[number]
12:[of]
13:[words]
14:[in]
15:[this]
16:[file]
17:[is]
18:[twenty]
19:[s'right]
paul@horus:~/src/sandbox$ 

请注意,这仅适用于您在 read_file() 中将数组声明为 static - 不要以这种方式返回指向具有自动存储持续时间的局部变量的指针。

关于c - 在 C 中返回二维数组…,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579333/

相关文章:

c++ - 为什么缓冲区末尾和保存的帧指针之间有 8 个字节?

c++ - 通过函数传递数组

ios - 如何在 Swift 中创建一个空数组?

arrays - 快速对两个参数的数组进行排序

python - 如何找到列表交集?

字符转十六进制?

c - 是否可以从汇编文件中引用 C 枚举?

c - C 中的多维数组出现错误

c - Ruby C gem 运行之间的内存污染

java - 将数组中的多个字符串打印为单个字符串