Wow that was a quick turnaround!
A few weeks ago I managed to do something similar to this, just by copying an example from the internet (link below) and modifying it very slightly. This runs perfectly on the Teensy:
//main code from http://anyexample.com/programming/c/qsort__sorting_array_of_listItems__integers_and_structs.xml
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *listItems[] = { "Zorro", "Alex", "Allan", "Celine", "Bill super long name to test what happens to super long names", "Forest", "Dexter" };
size_t listItems_len = sizeof(listItems) / sizeof(char *);
void setup()
{
Serial.begin(9600);
/* print unsorted string array */
for(int i=0; i<listItems_len; i++){
Serial.println(listItems[i]);
}
Serial.println("Result:");
/* sort array using qsort functions */
QSort();
/* print sorted string array */
for(int i=0; i<listItems_len; i++){
Serial.println(listItems[i]);
}
}
void loop(){
}
//sort alphabetically
void QSort(){
/* sort array using qsort functions */
// listItems.toCharArray(listItemsChar,sizeof(listItemsChar);
size_t listItems_len = sizeof(listItems) / sizeof(char *);
qsort(listItems, listItems_len, sizeof(char *), cstring_cmp);
}
/* qsort C-string comparison function */
int cstring_cmp(const void *a, const void *b){ //edited C version of this function from //https://www.benjaminwuethrich.dev/2015-03-07-sorting-strings-in-c-with-qsort.html
const char *ia = *(const char **)a;
const char *ib = *(const char **)b;
return strcmp(ia, ib);
/* strcmp functions works exactly as expected from
comparison function */
}
The only difference I can see between this and my version is how the char * array is populated/allocated in memory.
To the best of my understanding, in this example the array is in the stack, and its size is determined when declared. For the SD browser version it all gets populated and allocated dynamically.
Is there a difference (besides where the array is stored) between:
char *myarr[] = { "string1", "string2"};
and
#define arrStrings 100
char *myarr[arrStrings]; //list of strings
#define stringLen 100
char tempString[stringLen]; //temporary to store string ready to add to char * array
void setup(){
//assign first string to array
sprintf(tempString, "%s", "string1");//save file name to temporary string
myarr[0] = (char *)malloc(strlen(tempString) + 1);//assign enough memory for the new string
sprintf(myarr[0],"%s",tempString); //add new string into first element of char * array
//assign second string to array
sprintf(tempString, "%s", "string2");//save file name to temporary string
myarr[1] = (char *)malloc(strlen(tempString) + 1);//assign enough memory for the new string
sprintf(myarr[1],"%s",tempString); //add new string into second element of char * array
//etc
}
which I am overlooking?
Does this store the arrays differently, and therefore confuse qsort?