Home > OS >  How to allocate array dynamically
How to allocate array dynamically

Time:05-26

In this code i am opening a directory and creating an array of elements present in that directory so for that i have to first check number of element(arr_len) present in that directory so that i can give my array that size. And after this i am creating an arr[arr_len] like this. I want to dynamically give memory according to number of elements present in directory. using malloc, calloc, realloc or anything else.

DIR *dr = opendir("/path/");
if (dr == NULL) {
     printf("Could not open current directory" );
     return 0;
}
closedir(dr);

DIR *dr_ = opendir("/path/");
if (dr_ == NULL)    {
     printf("Could not open current directory" );
     return 0;
}

int i=0;
int arr[arr_len];
json_object *jobj = json_object_new_object();
while ((de = readdir(dr_)) != NULL){
     if ((strcmp(de->d_name, ".") != 0) && (strcmp(de->d_name, "..") != 0)){
         char file_name[50];
         strcpy(file_name, de->d_name);
         char *strarr[10];
         unsigned char *token = strtok(file_name, "-");
         int j =0;
         while (token!=NULL){
               strarr[j  ] = token;
               token = strtok(NULL, "-");
         }
         int val = atoi(strarr[1]);
         arr[i] = val;
         i  ;
         json_object_object_add(jobj, strarr[1], json_object_new_string(de->d_name));
    }
}
closedir(dr_);

CodePudding user response:

You could use realloc(). The typical usage would be:

int arr_size = 0;
int *arr = NULL;

// extending by 1 element

int *new_arr = realloc(arr, (arr_size   1) * sizeof *new_arr);
if (!new_arr) { ... error handling ... }
arr = new_arr;
arr[arr_size  ] = ...

If the program is expected to critically fail on failure of realloc() then you could simplify the program by omitting new_arr.

arr = realloc(arr, (arr_size   1) * sizeof *arr);
if (!arr) { ... error message and exit program ... }
  • Related