C 动态分配结构的数组

C 动态分配结构的数组,c,malloc,C,Malloc,我很难在C中处理malloc,尤其是在分配结构数组时。我有一个程序,它基本上将所有文件名和文件大小存储在一个struct数组中。我在没有使用malloc的情况下让我的程序工作,但我真的不喜欢这种编程方式。在我的程序中使用malloc可以得到任何帮助吗 int getNumberOfFiles(char *path) { int totalfiles = 0; DIR *d; struct dirent *dir; struct stat cstat; d = opendir(path)

我很难在C中处理malloc,尤其是在分配结构数组时。我有一个程序,它基本上将所有文件名和文件大小存储在一个struct数组中。我在没有使用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是fileStruct结构的大小为totalfiles的数组。要使用分配,我们可以写:

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

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


当您尝试使用
malloc
创建数组时,您可能会发现
calloc
更直观,而不是向我们展示什么可以使用VLA,而是向我们展示什么不起作用。
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);
}