简体   繁体   English

在C中返回2d数组...

[英]returning 2d array in C…

I'm a total noob in C. I can't make the connect between this function and main. 我是C中的总菜鸟。我无法在此功能和主要功能之间建立连接。 I'm trying to print out a 2d array and I keep getting segmentation fault. 我正在尝试打印出2d阵列,并且我一直在分段故障。 Any help would be greatly appreciated. 任何帮助将不胜感激。

EDIT: When I changed the last line 'printf("%d:[%s]\\n",i,*(p+i))' from %s to %c, I get the first word in the file i'm reading from. 编辑:当我将最后一行'printf(“%d:[%s] \\ n”,i,*(p + i))'从%s更改为%c时,我得到文件中的第一个单词i'我在读。 So turns out that something is in fact being returned from my function. 事实证明事实上我的功能正在返回。 Now just need to figure out how to get it to return words from other lines in the file. 现在只需要弄清楚如何让它从文件中的其他行返回单词。

#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);
}

In general, you should be creating your array in main() and passing it in, this kind of behavior is very unorthodox. 通常,您应该在main()创建数组并将其传入,这种行为非常不正统。 However, if you do insist on doing it this way, you have to return a pointer to your array, since you cannot return arrays in C. 但是,如果你坚持这样做,你必须返回一个指向你的数组的指针,因为你不能在C中返回数组。

This is the kind of thing you'll need: 这是你需要的东西:

#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;
}

which, with a suitable input file, outputs: 其中,使用合适的输入文件输出:

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$ 

Note this only works because you declared your array in read_file() as static - don't return pointers to local variables with automatic storage duration in this way. 请注意,这只能起作用,因为您将read_file()数组声明为static - 不以这种方式返回具有自动存储持续时间的本地变量的指针。

Try moving your #define s back and changing your function header to return a pointer to arrays of size_strings characters, as follows: 尝试移动#define并更改函数头以返回指向size_strings字符数组的指针,如下所示:

    #define num_strings 20
    #define size_strings 20

    char (*read_file())[size_strings] {

Or alternately, with a typedef: 或者,使用typedef:

    #define num_strings 20
    #define size_strings 20

    typedef char (*PCharArr)[size_strings];

    PCharArr read_file() {

...and change the type of p in main accordingly: ...并相应地更改main中的p类型:

    char (*p)[size_strings];

That will return (a pointer to the first element of) an array of character arrays, which is more or less equivalent to a 2D array of char . 这将返回(指向第一个元素的指针)一个字符数组数组,它​​或多或少等同于一个二维char数组。

Update, oh I see, you pasted the code from main to the function, I know what happened here, you assumed p[20][20] is the same as ap* or maybe ap**, that's not correct, since now if you do *(p+1), the compiler doesn't know each element in p is 20 wide instead of 1 wide. 更新,哦,我看,你把代码从main粘贴到函数,我知道这里发生了什么,你假设p [20] [20]与ap *或者ap **相同​​,这是不正确的,因为现在如果你做*(p + 1),编译器不知道p中的每个元素是20宽而不是1宽。 You approach here should be to declare a pointer to an array of strings in read_file and return that instead: 你在这里的方法应该是在read_file中声明一个指向字符串数组的指针并返回它:

static char text[num_strings][size_strings];
static char *texts[num_strings]

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


return texts;

your p should be char* not int*. 你的p应该是char *而不是int *。 You also need to terminate the loop if 20 items have been read in. 如果已读入20个项目,您还需要终止循环。

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

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