problem with char** array

I have a problem with the following code. function File.name() return char pointer to the file name. Having the char *files_array[file_number]. I want to write file name to the array. Instead of this every files_array[file_number] keeps pointer to File.name() (which is changing constantly), so at the end I got the array full of the pointers to the last file name. Do you know how to fix it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Filenames(File dir) { // dir - directory
  int file_number = 0;
  while (true) {
    File entry =  dir.openNextFile(); // open next file
    if (! entry) {  //No more files
     dir.rewindDirectory(); // go back to starting directory
     break;
      }
     files_array[file_number] = new char [strlen(entry.name())];
     files_array[file_number] = entry.name();
     file_number++; 
   entry.close();
  }
}


This line creates the space to store the filename and assigns the pointer to your array.
files_array[file_number] = new char [strlen(entry.name())];

then this line assigns the pointer from entry.name() over the pointer from new.
files_array[file_number] = entry.name();

You need to strcpy entry.name() to files_array[file_number].
Last edited on
Line 10 you assign the pointer (the memory allocated on line 9 is leaked).

So instead of assigning the pointer you need to copy the content:

strcpy(files_array[file_number], entry.name());

See:
http://www.cplusplus.com/reference/cstring/strcpy/?kw=strcpy
It worked. Thanks for help

Is there a possiblity to check if a field of array exists?
For example I have array files_array[file_number][strlen(entry.name())] like this
1
2
3
FILE.TXT
TEMPDATA.TXT
EXAMPLE.TXT


Now I want to check if files_array[0][10] exists.
Last edited on
*Set all the first dimensions elements of files_array to 0 before filling in the filenames to files_array (should be doing this anyway).
*Fill in the filenames.
*Check if the pointer of files_array[x] == to NULL and you know it's empty, if not it "exists".
Last edited on
Topic archived. No new replies allowed.