簡體   English   中英

返回字符串數組時類型沖突

[英]Conflicting types when returning array of strings

我想從getListOfFiles()捕獲一個文件名(字符串)數組,並在我的主目錄中使用它。 我已經嘗試了所有想法,但仍然出現錯誤:

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

什么是真正的問題,原因是我認為所有類型和指針看起來都很好?

閱讀警告: implicit declaration of function 'getListOfFiles'

您正在使用之前從未見過的getListOfFiles(),因此假定它返回一個int值。 您可以通過在定義函數之前先聲明函數來解決。 char** getListOfFiles(char *path)在文件頂部附近,對於這種簡單情況,只需將整個定義移到main()之前

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM