[英]C realloc inside a function
這是我的代碼:
#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 of array”。 如果你想重新分配那個數組,你必須通過引用傳遞它(傳遞一個指向它的指針)所以你需要一個“ 指向字符串數組的指針 ”,或者一個char ***
:
... myfunc(char ***result, ...)
{
*result = realloc(*result, ...); // writing *result changes caller's pointer
}
...
char **data = ...;
myfunc(&data, ...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.