I am trying to sort a string array in C (char**), the string array is an array of all the names of files in a directory. Here are all the parts of the code, I expect the code to sort the array alphabetically, but it doesn't work. Here is the code to get the files from the directory
typedef struct
{
char** names;
int32_t count;
} Files;
void swap(char* a, char* b)
{
char* temp = a;
a = b;
b = temp;
}
void bubbleSort(char** strs, uint32_t length)
{
uint32_t i = 0, j = 0;
for (i = 0; i < length; i++)
{
for (j = 0; j < length - i - 1; j++)
{
if (strcmp(strs[j], strs[j + 1]) < 0)
{
swap(strs[j], strs[j + 1]);
}
}
}
}
Files* getScannableFilesInDir(char* dirname)
{
Files* files = (Files*)malloc(sizeof(Files));
files->names = NULL; //clearing garbage values
files->count = 0; //clearing garbage values
uint32_t dirnameLength = strlen(dirname);
uint32_t count = 0;
uint32_t countIterations = 0;
DIR* d = opendir(dirname);
struct dirent* dir = NULL;
while ((dir = readdir(d)) != NULL)
{
if (files->names == NULL) //first file, if START_AMOUNT is set to 0 we want to allocate enough space for the first path, once we know there is at least 1 file
{
files->names = (char**)malloc(1 * sizeof(char*));
count++; // there is enough space allocated for 1 string
}
if (strcmp(dir->d_name, ".") && strcmp(dir->d_name, "..") && dir->d_type != DT_DIR)
{
++countIterations;
if (count < countIterations)
{
files->names = (char**)realloc(files->names, countIterations * sizeof(char*)); //adding 1 more space
}
files->names[countIterations - 1] = (char*)malloc(sizeof(char) * (strlen(dir->d_name) + dirnameLength) + 2); //-1 because we are incrementing at the start of the loop and not the end
//+ 2 at the end because a. the \0 at the end, b. 1 space for adding the slash
strcpy(files->names[countIterations - 1], dirname);
files->names[countIterations - 1][dirnameLength] = '/'; //changing the \0 to /
strcpy(files->names[countIterations - 1] + (dirnameLength + 1), dir->d_name); //adding the name after the /, now we have the full name
}
}
closedir(d);
files->count = countIterations;
bubbleSort(files->names, files->count);
return files;
}
I checked the rest of the code, I am not changing the value of the files->names at any other point of the code, just reading it.