我试图创建一个以char **作为参数并返回char **类型的函数。此函数的目的是按字母顺序对字符串列表进行排序。我有这个代码,我无法弄清楚为什么我的代码不起作用。我看到这个答案“Returning an array of strings in C”,但我仍然无法弄清楚为什么下面的代码会崩溃......
这是我的代码:
#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;
}