1

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void mp3files(char** result, int* count, const char* path) {
    struct dirent *entry;
    DIR *dp;

    dp = opendir(path);
    if (dp == NULL) {
        printf("Error, directory or file \"%s\" not found.\n", path);
        return;
    }

    while ((entry = readdir(dp))) {
        if ((result = (char**) realloc(result, sizeof (char*) * ((*count) + 1))) == NULL) {
            printf("error");
                return;
        }

        result[*count] = entry->d_name;
        (*count)++;
    }

    closedir(dp);
}

int main() {

    int* integer = malloc(sizeof (int));
    *integer = 0;

    char** mp3FilesResult = malloc(sizeof (char*));
        mp3files(mp3FilesResult, integer, ".");

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

    return (EXIT_SUCCESS);
}

它给了我分段错误。然而,当我把这个循环:

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

mp3files功能结束时,它可以工作。当我mp3files从“。”更改函数的第三个参数时 到包含少于 4 个文件或目录的目录,它工作得很好。换句话说,当变量mp3FilesResult指向少于 4 个字符串时,它不会因分段错误而失败。

为什么它一直这样做?

在此先感谢并为我的英语感到抱歉。

4

1 回答 1

4

您传入 a char **,一个指向 char 的指针的指针,它表示指向“字符串”的指针,该指针表示“字符串数组”。如果要重新分配该数组,则必须通过引用传递它(传递指向它的指针),因此您需要一个“指向字符串数组的指针”,或者char ***

... myfunc(char ***result, ...)
{
    *result = realloc(*result, ...); // writing *result changes caller's pointer
}


...
char **data = ...;
myfunc(&data, ...);
于 2011-05-11T20:28:59.843 回答