【发布时间】:2018-03-07 16:14:48
【问题描述】:
下面的代码将文件名存储在一个目录中作为char** - 称为files。最终,我需要将所有这些文件名存储在一个 char* 中。所以我认为逻辑上我需要做的第一件事是找出这些字符串数组占用了多少内存,然后分配一个这个大小的char*。我对从堆技术进行分配不是很熟悉。如何确定char** 占用多少内存?
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <malloc.h>
size_t file_list(const char *path, char ***ls) {
size_t count = 0;
size_t length = 0;
DIR *dp = NULL;
struct dirent *ep = NULL;
dp = opendir(path);
if(NULL == dp) {
fprintf(stderr, "no such directory: '%s'", path);
return 0;
}
*ls = NULL;
ep = readdir(dp);
while(NULL != ep){
count++;
ep = readdir(dp);
}
rewinddir(dp);
*ls = calloc(count, sizeof(char *));
count = 0;
ep = readdir(dp);
while(NULL != ep){
(*ls)[count++] = strdup(ep->d_name);
ep = readdir(dp);
}
closedir(dp);
return count;
}
int main(int argc, char **argv) {
char **files;
size_t count;
int i;
count = file_list("/home/rgerganov", &files);
for (i = 0; i < count; i++) {
printf("%s\n", files[i]);
}
}
【问题讨论】:
-
你
malloc()一个已知的字节数,那么你为什么不跟踪它呢?此外,除非您 100% 确定要将 ALL 元素初始化为 0,或者您真的知道自己在做什么,否则不要使用calloc()。跨度>
标签: c pointers memory heap-memory