gpt4 book ai didi

C 在函数内部重新分配

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:43 24 4
gpt4 key购买 nike

这是我的代码:

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com