函数C内的realloc [英] C realloc inside a function
问题描述
下面是我的code:
#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);
}
这给了我segmetation故障。然而,当我把这个循环:
It gives me segmetation fault. However, when I put this loop:
for (int i = 0; i < *integer; i++) {
printf("ok, count: %d \n", *integer);
printf("%s\n", mp3FilesResult[i]);
}
在mp3files函数的最后,它的工作原理。而当我改变mp3files第三parametr的功能。到包含小于4的文件或目录的目录,它的伟大工程。换句话说,当小于4个字符串变量mp3FilesResult点,它不会失败,Segmetation故障。
in the end of mp3files function, it works. And when I change the third parametr of mp3files function from "." to a directory which contains less then 4 files or directories, it works great. In other words, when variable mp3FilesResult points at less then 4 strings, it doesn't fail with Segmetation fault.
为什么它继续做下去?
Why does it keep doing it ?
在此先感谢和抱歉,我的英语水平。
Thanks in advance and sorry for my english.
推荐答案
您传递一个的char **
,一个指向字符指针,这是重新presenting指针弦,这是重新presenting字符串数组。如果你想重新分配数组,你必须通过引用传递它(一个指针传递给它),所以你需要一个的指针的字符串数组,或的char ** *
:
You pass in a char **
, a pointer to a pointer to char, which is representing pointer to "string" which is representing "array of string". If you want to reallocate that array you must pass it by reference (pass a pointer to it) so you need a "pointer to array of string", or a char ***
:
... myfunc(char ***result, ...)
{
*result = realloc(*result, ...); // writing *result changes caller's pointer
}
...
char **data = ...;
myfunc(&data, ...);
这篇关于函数C内的realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!