I try to write function that return array of string(all files and folders that located in some directory). Code is below. When I use this code for output info to console (using comented code below) it work great, but when I am try return pointer to pointer to wchar_t I obtain array where every element is equal to enother(all elements are the same). What I do wrong?
wchar_t path[SIZE];
wchar_t *PathCreator(wchar_t *dir, wchar_t *fileName)
{
int j = 0;
while(j < SIZE)
{
path[j] = '\0';
j++;
}
int i;
i = 0;
while(*dir != '*' && *dir != '\0')
{
path[i] = *dir;
i++;
dir++;
}
wchar_t *t = fileName;
while(*t != '\0')
{
path[i] = *t;
i++;
t++;
}
path[i] = '\0';
return path;
}
wchar_t* allFlsArr[SIZE];
int i = 0;
wchar_t **GetAllFiles(wchar_t* dir)
{
WIN32_FIND_DATA file;
HANDLE search_hendle = FindFirstFile(dir, &file);
if(search_hendle)
{
do
{
wchar_t *p = PathCreator(dir,file.cFileName);
//std::wcout << p << std::endl;
allFlsArr[i++] = p;
std::wcout << i << std::endl;
}
while(FindNextFile(search_hendle, &file));
allFlsArr[i] = '\0';
}
CloseHandle(search_hendle);
return allFlsArr;
}
I would suspect you are not allocating the memory for the return from PathCreator. This means you set the same pointer at every entry. When you change the data at the pointer location it gets changed and as every entry is looknig at that data everything gets “changed”.
You would be far better off using std::wstring …
You would need to change the corresponding code in PathCreator to use std::wstring as well.
Edit: If you really won’t use STL then you need to modify PathCreator to do something like the following:
Don’t forget to delete[] the strings when you’ve finished with them!
You really are, however, creating pain for yourself by not using the STL functions and the RAII bonuses that they provide. My method would require no remembering to delete the memory used afterwards as when it drops out of scope that memory will automatically be freed.
I really thing the first method is waaaay easier though.