Динамическое выделение массива структуры - PullRequest
0 голосов
/ 17 мая 2018

Мне трудно работать с malloc в C, особенно при выделении массива struct.У меня есть программа, которая в основном хранит все имена файлов и размер файла в массиве 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 (), чтобы получить размер для статического размещения.

1 Ответ

0 голосов
/ 17 мая 2018
struct fileStruct fileobjarray[totalfiles];

fileobjarray - это массив VLA общего размера файловой структуры fileStruct. Чтобы выделить с помощью 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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...