c - 动态分配结构体数组

标签 c malloc

我在处理 C 中的 malloc 时遇到了困难,尤其是在分配结构数组时。我有一个程序,基本上将所有文件名和文件大小存储在一个结构数组中。我的程序在不使用 malloc 的情况下运行,但我不太喜欢这种编程方式。我可以在程序中使用 malloc 获得任何帮助吗?

int getNumberOfFiles(char *path)
{
 int totalfiles = 0;
 DIR *d;
 struct dirent *dir;
 struct stat cstat;
 d = opendir(path);
 while(( dir = readdir(d)) != NULL) {
     totalfiles++;
}
return totalfiles;
}

int main()
{

      int totalfiles = getNumberOfFiles(".");
      int i =0;
      DIR *d;
      struct dirent *dir; 
      d = opendir(".");
      struct fileStruct fileobjarray[totalfiles];
      struct stat mystat;

       while(( dir = readdir(d)) != NULL) {
        fileobjarray[i].filesize=mystat.st_size;
        strcpy (fileobjarray[i].filename ,dir->d_name );
        i++;
      }

}

如您所见,我创建了一个名为 getnumberoffiles() 的函数来获取静态分配的大小。

最佳答案

struct fileStruct fileobjarray[totalfiles];

fileobjarray 是 VLA fileStruct 结构的大小为 Totalfiles 的数组。使用 malloc 进行分配我们可以写:

struct fileStruct *fileobjarray = malloc(totalfiles * sizeof(*fileobjarray));

我们将为 totalfiles 元素数组分配内存,每个元素的 sizeof(*fileobjarray) = sizeof(struct fileStruct) 大小。有时calloc在 C 中更可取,因为它可以(在某些平台上)防止溢出:

struct fileStruct *fileobjarray = calloc(totalfiles, sizeof(*fileobjarray));

并记住free()

int getNumberOfFiles(char *path)
{
 int totalfiles = 0;
 DIR *d;
 struct dirent *dir;
 struct stat cstat;
 d = opendir(path);
 while(( dir = readdir(d)) != NULL) {
     totalfiles++;
}
return totalfiles;
}

int main()
{

      int totalfiles = getNumberOfFiles(".");
      int i =0;
      DIR *d;
      struct dirent *dir; 
      d = opendir(".");
      struct fileStruct *fileobjarray = calloc(totalfiles, sizeof(*fileobjarray));
      if (fileobjarray == NULL) {
            fprintf(stderr, "Error allocating memory!\n");
            return -1;
      }
      struct stat mystat;

      while(( dir = readdir(d)) != NULL) {
        fileobjarray[i].filesize=mystat.st_size;
        strcpy (fileobjarray[i].filename ,dir->d_name );
        i++;
      }
      free(fileobjarray);
}

关于c - 动态分配结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50380082/

相关文章:

c - valgrind 错误大小 8 的无效读取

c - Firebase如何从ESP32/Arduino获取数据

c++ - 如何判断是否使用了 glibc

c - 使用 C 进行试验 - 为什么我不能分配和使用 2GB 内存?

c - 尝试将文件读入链接列表但程序在读取时崩溃

c - 操作内存时是否需要乘以sizeof(char)?

c - 不错的 C 字符串库

c - 您如何分析多核处理器的所有内核?

c - C 中 1 的无效写入大小

multithreading - ucLibc malloc 线程安全吗?