C 在函数内部重新分配

标签 c realloc

这是我的代码:

#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 个字符串时,它不会因段错误而失败。

为什么它一直这样做?

提前致谢,对不起我的英语。

最佳答案

您传入一个 char **,一个指向 char 指针的指针,它表示指向“string”的指针,“string”表示“字符串数组”。如果你想重新分配那个数组,你必须通过引用传递它(传递一个指向它的指针)所以你需要一个“指向字符串数组的指针”,或者一个char ***:

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


...
char **data = ...;
myfunc(&data, ...);

关于C 在函数内部重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5970151/

相关文章:

c - 用 C 从文件中读取其中的所有元素

c - 0 大于 0 的浮点值

c - 如何从共享内存中分离字符串数组? C

c - 重新分配**数组

c - 使用动态空指针数组进行重新分配时出错

更改结构内的数组大小

c - 多次使用 realloc 获取未知大小数组的好方法吗

c - 从文件中读取()返回什么?

c++ - c/c++中用函数指针模仿OO,如何存储?

消费者生产者代码未声明的错误linux调试