交换char * array 导致问题

void sortArray(char* array[], int count){ int compare; int index; for(index = 0; index < count; index++){ //runs through array, keeping track of index for(compare = index; compare < count; compare++){ if (strcmp(array[compare] , array[index]) <= 0){ swap(*(array+compare), *(array+index)); } } } } void swap(char *strA, char *strB){ char *temp = (char *)malloc((strlen(strA)+1) * sizeof(char)); assert(temp!=NULL); strcpy(temp, strA); free(strA); strA=(char *)malloc((strlen(strB)+1) * sizeof(char)); assert(strA!=NULL); strA=strcpy(strA, strB); free(strB); strB= (char *)malloc((strlen(temp)+1) * sizeof(char)); assert(strB!=NULL); strcpy(strB, temp); free(temp); } 

给出输出:

 Array1[0]: Adam Pendleton Array1[1]: Jeison Ortega Array1[2]: Theodore Staake Array1[3]: Patrick Mahoney Array1[4]: Andrew Silberstein Array1[5]: Alan Boulais Array1[6]: Daniel Comeau Array1[7]: Sean Mikhael Array1[8]: Sarah Shank Array1[9]: Daniel Verge Array1[10]: Dhimitris Natsis Array1[11]: Kathleen Lent Array1[12]: Osei Collins Array1[13]: Jason Hintlian Array1[14]: Michael Gibson Array1[15]: Alex Grossi Array1[16]: Michael Svedberg Array1[17]: Randall White Array1[18]: Alvin Cordor Array1[19]: Rodrigo Roldan Array1[20]: Matthew McArthur Array1[21]: Jesse Anaya Sorted Array1[0]: Adam Pendleton Sorted Array1[1]: Patrick Mahoney Sorted Array1[2]: Theodore Staake Sorted Array1[3]: Sarah Shank Sorted Array1[4]: Dhimitris Natsis Sorted Array1[5]: Alan Boulais Sorted Array1[6]: Alex Grossi Sorted Array1[7]: Alvin Cordor Sorted Array1[8]: Sean Mikhael Sorted Array1[9]: Osei Collins Sorted Array1[10]: Michael Svedberg Sorted Array1[11]: Daniel Comeau Sorted Array1[12]: Daniel Verge Sorted Array1[13]: Jason Hintlian Sorted Array1[14]: Jesse Anaya Sorted Array1[15]: Michael Gibson Sorted Array1[16]: Matthew McArthur Sorted Array1[17]: Randall White Sorted Array1[18]: Rodrigo Roldan Sorted Array1[19]: Kathleen Lent <-----not sure why this is dupe Sorted Array1[20]: <-----not sure why this is here Sorted Array1[21]: Kathleen Lent 

我不确定这些空白区域的来源或为什么有重复的名称。 我甚至创建了另一个名为reverseArray的函数,它只交换了第一个和最后一个字符串,看起来问题源于交换函数,我的猜测是,当它复制字符串时,那里有一些混乱。

因为这只是正在进行的一小部分,我已经逐行读取文件中的文本以使用名称字符串填充char * array [],这可以正常工作,因为arrays打印正确之前排序。

我还不确定你的确切问题,但你可以通过交换数组中字符串的位置来做一个更简单,更有效的工作,而不是更改字符串本身:

 void sortArray(char* array[], int count) { int compare; int index; char *tmp; for(index = 0; index < count; index++) { for(compare = index; compare < count; compare++) { if (strcmp(array[compare], array[index]) <= 0) { tmp = array[compare]; array[compare] = array[index]; array[index] = tmp; } } } } 

您的代码的确切问题是您的swap()函数释放传递给它的两个指针,并且不返回指向它以任何forms分配的新内存的指针。 因此,您正在排序的数组中的所有指针最终都指向已释放的内存 – 这是一个奇迹,它根本就可以工作。

要解决此问题,您可以更改swap()的签名以通过引用获取两个指针:

 void swap (char **strA, char **strB) 

并将指针传递给它:

 swap(array+compare, array+index); 

话虽如此,从长远来看,Claudiu建议您只是交换指针而不是复制数据可能是一个更好的主意。 🙂