如何在c中返回char数组指针。

时间:2018-01-18 06:01:13

标签: c arrays pointers char return

char* GetCollection()
{
    FILE *collection;
    char val1[15] = "collection.txt";
    collection = fopen(val1,"r");

    char readingline[10];
    char *listofurls[10];
    *listofurls = malloc(10 * sizeof(char));
    int j= 0,k,m=0,p, nov=0, q, r;

    while (fscanf(collection, "%s", readingline)==1) {

        listofurls[j] = malloc(10*sizeof(char));

        strcpy(listofurls[j],readingline);

        j++;
        nov++;
        }

    for (k = 0 ; k < nov ; k++)
        printf("%s\n", listofurls[k]);

    fclose(collection);
    return listofurls;
}

我想从GetCollection方法返回listofurls并在main方法中使用它。我无法在main方法中捕获返回值。

2 个答案:

答案 0 :(得分:4)

你不能这样做 - 尽管它指向的内存的寿命超出了函数的范围 - 数组却没有。阵列具有自动存储持续时间。所以你不能这样做。尝试在声明它的范围之外访问它会调用未定义的行为。

简单的解决方案,动态分配包含char*的内存。 (另一种方法是将数组包装在struct内,然后从函数中返回。)

#define MAXSIZE 10
...
...
char **listofurls;
listofurls = malloc(sizeof *listofurls * MAXSIZE);
if( !listofurls ){
    perror("malloc");
    exit(1);
}
...
return listofurls;

实际上,不清楚为什么突然为指针0数组中的listofurls指针分配内存。有一个内存泄漏。您没有检查fopen的返回值。检查是否成功打开文件。

随着提议的更改,函数的签名将是

char** GetCollection();

通过这些更改,您将在main()

中保留返回值
char** p = GetCollection();

与此一起,当你完成它时,你将释放这个分配的内存。

答案 1 :(得分:0)

如果确实想要返回一个数组,你可以将它包装在这样的Webhooks中,但我更喜欢@ coderredoc的struct解决方案。

malloc

打开编译器警告,#include <stdio.h> #include <stdlib.h> #include <string.h> struct MyStruct { char* listofurls[10]; }; struct MyStruct GetCollection() { FILE *collection; char val1[15] = "collection.txt"; collection = fopen(val1,"r"); if (collection == NULL) { fprintf(stderr, "Unable to open file %s\n", val1); exit(-1); } char readingline[10]; struct MyStruct myStruct; int j= 0,k, nov=0; while (fscanf(collection, "%s", readingline)==1) { myStruct.listofurls[j] = malloc(10); //sizeof(char) is always 1 if (myStruct.listofurls[j] == NULL) { fprintf(stderr, "Unable to malloc for string %d\n", j); } else { strcpy(myStruct.listofurls[j],readingline); } j++; nov++; } for (k = 0 ; k < nov ; k++) printf("%s\n", myStruct.listofurls[k]); fclose(collection); return myStruct; } int main(void) { struct MyStruct myStruct = GetCollection(); for (int i=0; i<10; i++) { printf("%s\n", myStruct.listofurls[i]); free(myStruct.listofurls[i]); } return 0; } 应该足够了......你有几个,包括尝试返回本地数组。始终检查可能返回错误的函数调用的返回值(-Wall -Wextrafopen