C语言 字符串指针排序函数

下面这个是用冒泡排序,运行错误

#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
  char ptr[N][80]={ "how ","are ","you ","i","fine" };
  char *p[N];
  char *temp;
  int i,j;
  for(i=0;i<N;i++)  p[i]=ptr[i];

   for(i=0;i<N-1;i++)
      for(j=0;j<N-i;j++)
          if(strcmp(p[j],p[j+1])>0)
          {
            temp=p[j];
            p[j]=p[j+1];
            p[j+1]=temp;
          }
  for(i=0;i<N;i++)
      puts(p[i]);
}

下面这个是用选择排序,运行结果却是正确的

#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
  char ptr[N][80]={ "how ","are ","you ","i","fine" };
  char *p[N];
  char *temp;
  int i,j;
  for(i=0;i<N;i++)  p[i]=ptr[i];

   for(i=0;i<N-1;i++)
      for(j=i+1;j<N;j++)
          if(strcmp(p[i],p[j])>0)
          {
            temp=p[j];
            p[j]=p[i];
            p[i]=temp;
          }
  for(i=0;i<N;i++)
      puts(p[i]);
}

下面这个没有用指针,直接改变原字符串数组,是用冒泡排序
也是正确的

#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
  char ptr[N][80]={ "how ","are ","you ","i","fine" };
  char temp[80];
  int i,j;
   for(i=0;i<N-1;i++)
      for(j=0;j<N-i;j++)
          if(strcmp(ptr[j],ptr[j+1])>0)
          {
            strcpy(temp,ptr[j]);
            strcpy(ptr[j],ptr[j+1]);
            strcpy(ptr[j+1],temp);
          }
  for(i=0;i<N;i++)
      puts(ptr[i]);
}


求解答,万分感谢!

第一个程序


#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
  char ptr[N][80]={ "how ","are ","you ","i","fine" };
  char *p[N];
  char *temp;
  int i,j;
  for(i=0;i<N;i++)  
      p[i]=ptr[i];

   for(i=0;i<N-1;i++)
      for(j=i;j<N-1;j++)
          if(strcmp(p[j],p[j+1])>0)
          {
            temp=p[j];
            p[j]=p[j+1];
            p[j+1]=temp;
          }
  for(i=0;i<N;i++)
      puts(p[i]);
}

各种错
第一段:i=0改为i=1。原因:当i = 0时,j<N-i,j的最大值可以是4,p[j+1])即为p[5],指针数组越界了,p[5]是一个未初始化的地址
第二段:这种选择排序不好,多次赋值,不多说
第三段:其实也是错的,原因和1差不多,不过ptr[5]碰巧是有效地址,但是ptr[5]得内容绝对是乱码

第二个程序,你不是选择排序,选择排序写法如下

 #include<stdio.h>
#include<string.h>
#define N 5
int main()
{
  char ptr[N][80]={ "how ","are ","you ","i","fine" };
  char *p[N];
  char *temp;
  int i,j;
  for(i=0;i<N;i++)  
      p[i]=ptr[i];

   for(i=0;i<N;i++)
   {
    int minidx = i;
    for (j = i+1; j < N; j++)
    {
        if(strcmp(p[minidx],p[j])>0)
        {
            minidx=j;
        }
        temp=p[i];
        p[i]=p[minidx];
        p[minidx]=temp;
    }
   }
  for(i=0;i<N;i++)
      puts(p[i]);
}