下面主函数调用函数SortString()按奥运会参赛国国名在字典中的顺序对其入场次序进行排序,请问程序错在哪里? 不懂,输入几个字符串后就自动退出了

#include  <stdio.h>
#include  <string.h>
#define   M  150 /* 最多的字符串个数 */
void SortString(char *ptr[], int n);
int main()
{
  int    i, n; 
  char   *pStr[M];
  printf("How many countries?");
  scanf("%d",&n);
  getchar();        /* 读走输入缓冲区中的回车符 */
  printf("Input their names:\n");
  for (i=0; i<n; i++)  
  {
      gets(pStr[i]);  /* 输入n个字符串 */
  }
  SortString(pStr, n); /* 字符串按字典顺序排序 */
  printf("Sorted results:\n");
  for (i=0; i<n; i++)                    
  {
      puts(pStr[i]);  /* 输出排序后的n个字符串 */
  }
  return 0;
}
void SortString(char *ptr[], int n)
{
  int   i, j;
  char  *temp = NULL;
  for (i=0; i<n-1; i++)    
  {
      for (j=i+1; j<n; j++)
      {
         if (strcmp(ptr[j], ptr[i]) < 0)    
         {
              temp = ptr[i];
              ptr[i] = ptr[j];
              ptr[j] = temp;
         } 
      }   
  } 
}

这么改下,供参考:

#include  <stdio.h>
#include  <string.h>
#define   M  150 /* 最多的字符串个数 */
void SortString(char* ptr[], int n);
int main()
{
    int    i, n;
    char* pStr[M], p[M][M];
    printf("How many countries?");
    scanf("%d", &n);
    getchar();        /* 读走输入缓冲区中的回车符 */
    printf("Input their names:\n");
    for (i = 0; i < n; i++)
    {
        gets(p[i]);  /* 输入n个字符串 */
        pStr[i] = p[i];
    }
    SortString(pStr, n); /* 字符串按字典顺序排序 */
    printf("Sorted results:\n");
    for (i = 0; i < n; i++)
    {
        puts(pStr[i]);  /* 输出排序后的n个字符串 */
    }
    return 0;
}
void SortString(char* ptr[], int n)
{
    int   i, j;
    char* temp = NULL;
    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (strcmp(ptr[j], ptr[i]) < 0)
            {
                temp = ptr[i];
                ptr[i] = ptr[j];
                ptr[j] = temp;
            }
        }
    }
}


#include  <stdio.h>

#include  <string.h>

#define   M  150 /* 最多的字符串个数 */

void SortString(char *ptr[], int n);

int main()

{

  int    i, n; 

  char   **pStr;

  printf("How many countries?");

  scanf("%d",&n);

  getchar();        /* 读走输入缓冲区中的回车符 */

  printf("Input their names:\n");

  pStr = (char*)malloc(sizeof(char) * n);

  for (i=0; i<n; i++)  

  {
      pStr[i] = (char*)malloc(sizeof(char) * M);
      gets(pStr[i]);  /* 输入n个字符串 */

  }

  SortString(pStr, n); /* 字符串按字典顺序排序 */

  printf("Sorted results:\n");

  for (i=0; i<n; i++)                    

  {

      puts(pStr[i]);  /* 输出排序后的n个字符串 */

  }

  free(pStr);

  return 0;

}

void SortString(char *ptr[], int n)

{

  int   i, j;

  char  temp[M];

  for (i=0; i<n-1; i++)    

  {

      for (j=i+1; j<n; j++)

      {

         if (strcmp(ptr[j], ptr[i]) < 0)    

         {
             strcpy(temp, ptr[i]);
             strcpy(ptr[i], ptr[j]);
             strcpy(ptr[j], temp);
         } 

      }   

  } 

}

运行结果:

img

地址出问题了,因为主函数里面的指针是野指针,在乱指位置。调试的时候会显示segment fault 警告,这种多半就是地址出问题了