-3
# define size_of_files 100
char* file_paths[size_of_files];

for(int file_path_idx = 0; file_path_idx < N; file_path_idx++)
{
     file_paths[file_path_idx] =(char*)malloc(strlen(fpath)+1);
        strcpy(file_paths[file_path_idx],fpath);
}

How to have malloc for file_paths array at ones not for every idx in file_path what i need is to have file_paths[file_path_idx] =(char*)malloc(strlen(fpath)+1); above the for loop and rhe strcpy will work fine?

joker
  • 3
  • 2
  • One allocation, one deallocation. 100 allocations, 100 deallocations. – tadman Mar 29 '21 at 19:04
  • 2
    Is the comparison correct? `file_path_idx > N;` yet `file_path_idx++` is increasing. Perhaps it should be `file_path_idx < size_of_files` – Weather Vane Mar 29 '21 at 19:09
  • 2
    Tip: If you know the *combined length* of all the strings you're copying you can do one big allocation for the whole buffer and copy them in there, end-to-end, including their NUL terminators. Note at this point you cannot release any one of them individually. It's either all or none. – tadman Mar 29 '21 at 19:21
  • Do your malloc calls in a loop. Better yet, maintain a counter at the end of the array, and malloc new elements as you need them. – Robert Harvey Mar 29 '21 at 19:35
  • 2
    What is `fpath` and how does its length relate to the lengths of `file_paths[file_path_idx]`? – Barmar Mar 29 '21 at 19:35
  • This seems apropos: [**Correctly allocating multi-dimensional arrays**](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) – Andrew Henle Mar 29 '21 at 19:42
  • @Barmar **fpath** is string i want to add to list, you need to malloc every one so you kan copy it to list – joker Mar 30 '21 at 06:42
  • @WeatherVane now it is, thanx for note – joker Mar 30 '21 at 06:45

1 Answers1

0

You can allocate a single block of memory containing size_of_files * (strlen(fpath)+1) bytes. Then you can index into this when making copies of fpath

# define size_of_files 100
char* file_paths[size_of_files];

size_t pathlen = strlen(fpath)+1;
char *all_paths = malloc(size_of_files * pathlen);

for(int file_path_idx = 0; file_path_idx < N; file_path_idx++)
{
    file_paths[file_path_idx] = &all_paths[file_path_idx * pathlen];
    strcpy(file_paths[file_path_idx], fpath);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612