I was trying to create a function that takes a char** as a parameter and returns a char** type. The purpose of this function is to sort a list of strings alphabetically. I have this code and I can't figure out why my code doesn't work. I saw this answer "Returning an array of strings in C", but I still can't figure out why the following code crushes...
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** a_to_z_ordering (char**, int);
int main(int argc, char **argv) {
char** unordered;
//char** ordered;
unordered = malloc(50*150); //is it ok to use more space? (In case my max is what the numbers declare)
//ordered = malloc(50*150); //should I declare like this?
for(int i = 0; i<50; i++) {
unordered[i] = malloc(150*sizeof(char));
}
//for(int i = 0; i<50; i++) {
// ordered[i] = malloc(150*sizeof(char));
//}
strcpy(unordered[0], "ba");
strcpy(unordered[1], "ab");
strcpy(unordered[2], "aa");
printf("The list of strings without alphabetical ordering:\n\n");
for (int i = 0; i<3; i++) {
printf("This is string %d: %s\n", i, unordered[i]);
}
//arrange strings to alphabetical ordering
char** ordered = a_to_z_ordering(unordered, 3); //3 elements + \0?
printf("\n\nThe list of strings WITH alphabetical ordering:\n\n");
for (int i = 0; i<3; i++) {
printf("This is string %d: %s\n", i, ordered[i]);
}
return 0;
}
char** a_to_z_ordering (char** arrayOfStrings, int arraySize) {
char* tempString = malloc(150*sizeof(char));
arrayOfStrings = malloc(50*150);
for(int i = 0; i<arraySize; i++) {
arrayOfStrings[i] = malloc(150*sizeof(char));
}
for(size_t i = 1; i < arraySize; i++) {
for(size_t n = 1; n <arraySize; n++) {
if(strcmp(arrayOfStrings[n-1], arrayOfStrings[n]) > 0) {
strcpy(tempString, arrayOfStrings[n-1]);
strcpy(arrayOfStrings[n-1], arrayOfStrings[n]);
strcpy(arrayOfStrings[n], tempString);
}
}
}
return arrayOfStrings;
}
unordered = malloc(50*150);totally wrong. You are allocating an array of 50 char pointers, the correct expression isunordered = malloc(50*sizeof(char*));char*'s in your sorting procedure?qsort? It is orders of magnitude faster than your manual sort and yourcomparefunction forqsort(the last parameter) can simply be written to sort ascending/descending, etc., however you choose. In your case, you are rewriting a complete sort routine where you would only need to write a compare function to useqsort(not to mention thatqsorthas been developed and validated with years of testing -- where your sort function may not be quite as -- proven, shall we say)