返回字符串数组时的冲突类型

时间:2018-04-03 21:57:46

标签: c

我想从getListOfFiles()中捕获一组文件名(字符串)并在我的main中使用它。我已经尝试了我的每个想法,但仍然出现错误:

gcc testowe.c -o test testowe.c: In function ‘main’:
testowe.c:8:15: warning: implicit declaration of function ‘getListOfFiles’ [-Wimplicit-function-declaration]
 char **list = getListOfFiles(argv[1]);

testowe.c:8:15: warning: initialization makes pointer from integer without a cast [-Wint-conversion]

testowe.c: At top level:
testowe.c:11:8: error: conflicting types for ‘getListOfFiles’
 char** getListOfFiles(char *path) {

testowe.c:8:15: note: previous implicit declaration of ‘getListOfFiles’ was here
 char **list = getListOfFiles(argv[1]);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main(int argc, char *argv[])
{
char **list = getListOfFiles(argv[1]);
}

char** getListOfFiles(char *path) {
    int n=0, i=0;
    DIR *d;
    struct dirent *dir;
    d = opendir(path);

    while((dir = readdir(d)) != NULL) {
        if ( !strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..") )
        {

        } else {
            n++;
        }
    }
    rewinddir(d);

    char **filesList;
    filesList = malloc((n + 1)*sizeof(char*));

    while((dir = readdir(d)) != NULL) {
        if ( !strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..") ){

        }else {
            filesList[i] = (char*) malloc (strlen(dir->d_name)+1);
            strncpy (filesList[i],dir->d_name, strlen(dir->d_name) );
            i++;
        }
    }
    filesList[i] = NULL;
    closedir(d);
    return filesList;
}

真正的问题是什么?我认为所有类型和指针看起来都很好?

1 个答案:

答案 0 :(得分:3)

阅读警告:implicit declaration of function ‘getListOfFiles’

您正在使用之前未见过的getListOfFiles(),因此假设它返回一个int。您可以通过在定义函数之前声明函数来解决。靠近文件顶部的char** getListOfFiles(char *path)或者对于这个简单的案例,只需在main()

之前移动整个定义