I am trying to qsort a dynamically-allocated 2d array, without success. I assume it has something to do with the dynamic allocation, because things work fine if I use a global 2d array (eg, fileList[148096][100]). Any ideas?
// global:
char **fileList;
void allocateFileListArray(void)
{
int arraySize = 148096;
int fileNameLength = 100;
/* allocate storage for an array of pointers */
fileList = (char **) malloc(arraySize * sizeof(char *));
/* for each pointer, allocate storage for an array of chars */
for (int i = 0; i < arraySize; i++)
{
if ((fileList[i] = (char *) malloc(fileNameLength * sizeof(char))) == NULL)
printf("failed fileList alloc\n");
}
}
void sortTheArray(int fileListCount)
{
qsort (( char * ) fileList, fileListCount, sizeof ( *fileList ),
(compfn) compareStrings );
}
int compareStrings(char *stackA, char *stackB)
{
int result;
result = strcmp( stackA->name, stackB->name);
return(result);
}
Your char filelist[4095][100] example is not the same as your allocation in allocateFileListArray, an array of pointers is not the same as an array of an array.
You should change the compare function for qsort like
and you can use this function without ugly cast in qsort.