使用冒号排序对字符串数组进行排序

Mic*_*GER 2 c sorting string algorithm bubble-sort

任何帮助将不胜感激.我试图按字母顺序排序12个字符串,使用冒泡排序包含在数组中,使用以下代码:

#include <stdio.h>
#include <string.h>
int main()
{
   //initialising variables and the array
   char *DT [12] = { "James Smith DT01 DT265A", "John Murphy DT02 DT265A", "Robert Lam DT03 DT265A", "Michael Martin DT04 DT265A", "William Brown DT05 DT265A", "David Roy DT06 DT265A", "Richard Tremblay DT07 DT265A", "Joseph Lee DT08 DT265A", "Thomas Gagnon DT09 DT265A", "Charles Wilson DT10 DT265A", "Chris Philips DT11 DT265A", "Henry Hill DT12 DT265A"  } ;
   char temp[100];
   int n = sizeof(DT)/sizeof(DT[0]);

   //Implementing Algorithm using bubble sort to sort string array
   //
   for (int j = 0 ; j < n - 1 ; j++ )
   {
      for (int i = j + 1 ; i < n ; i++ )
      {
         if( strcmp(DT[j], DT[i]) > 0 ) 
         {
            strcpy(temp, DT[j]);
            strcpy(DT[j], DT[i]);
            strcpy(DT[i], temp);
         }//end if
      }//end for
   }//end for
   printf("Strings in sorted order are : ");
   for (int i=0; i<n; i++)
   {
      printf("\n String %d is %s", i+1, DT[i]);
   }

   getchar();
   getchar();
   return 0;
}//end main()
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

排序顺序的字符串是:

字符串1是A.

字符串2是A.

字符串3是2vid Roy DT06 DT265A

字符串4是Roy DT06 DT265A

字符串5是Charles Wilson DT10 DT265A

字符串6是

String 7是Chris Philips DT11 DT265A

字符串8是06 DT265A

字符串9是avidRoy DT06 DT265A

字符串10是mith DT01 DT265David Roy Dyy DT06 DT265A

字符串11是y DT06 DT265A

字符串12是y DT06 DT265A

Som*_*ude 5

问题是您尝试覆盖文字字符串的内容,C中的文字字符串是只读字符数组.

不要试图复制字符串本身,而是复制指针.如在

char *temp = DT[j];
DT[j] = DT[i];
DT[i] = temp;
Run Code Online (Sandbox Code Playgroud)

另一种可能的解决方案是创建DT一个数组数组:

char DT[12][100] = { ... };
Run Code Online (Sandbox Code Playgroud)

确保辅助数组的大小足以容纳最长的字符串(加上一个,因为您当然也需要终结符的空间).

  • 细节:_String literals_可以被认为是学习者的"只读".然而写_string literals_是UB - 不是只读的.`strcpy()`可能"工作" - 它可能不会 - 它是UB. (2认同)