#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
  char **p2 = NULL;
  int num = 5;
  char *tmp = NULL;
  p2 = (char **)malloc(sizeof(char*) * num);     //为指针分配内存

  for (int i = 0; i < num; i++)              为每个字符串分配内存
  {
    p2[i] = (char*)malloc(sizeof(char) * 100);
    sprintf(p2[i], "%d%d%d", i+1, i+1, i+1);
  }
  printf("排序前\n");
  for (int i = 0; i < num; i++)
  {
    //printf("%s\n", *(p2 + i));
    printf("%s\n", p2[i]);
  }
  for (int i = 0; i < num; i++)
  {
    for (int j = i + 1; j < num; j++)
    {
      if (strcmp(p2[i], p2[j]) < 0)
      {
        tmp = p2[i];
        p2[i] = p2[j];
        p2[j] = tmp;
      }
    }
  }
  printf("排序后\n");
  for (int i = 0; i < num; i++)
  {
    //printf("%s\n", *(p2 + i));
    printf("%s\n", p2[i]);
  }
  for (int i = 0; i < num; i++)
  {
    if (p2[i] != NULL)
    {
      free(p2[i]);
      p2[i] = NULL;
    }
  }
  if (p2 != NULL)
  {
    free(p2);
    p2 = NULL;
  }
  system("pause");
  return 0;
}

同之前两种,优化成函数后:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **getMem(int num)    //分配内存
{
  char ** p2 = NULL;
  p2 = (char **)malloc(sizeof(char*) * num);
  if (p2 == NULL)
  {
    return -1;
  }
  for (int i = 0; i < num; i++)
  {
    p2[i] = (char*)malloc(sizeof(char) * 100);
    sprintf(p2[i], "%d%d%d", i + 1, i + 1, i + 1);
  }
  return p2;
}
void printfMem(char **p2,int num)    //输出字符串
{
  for (int i = 0; i < num; i++)
  {
    //printf("%s\n", *(p2 + i));
    printf("%s\n", p2[i]);
  }
}
void sortMem(char **p2, int num)   //排序
{
  char *tmp = NULL;
  for (int i = 0; i < num; i++)
  {
    for (int j = i + 1; j < num; j++)
    {
      if (strcmp(p2[i], p2[j]) < 0)
      {
        tmp = p2[i];
        p2[i] = p2[j];
        p2[j] = tmp;
      }
    }
  }
}
void freeMem(char **p2,int num)
{
  for (int i = 0; i < num; i++)
  {
    if (p2[i] != NULL)
    {
      free(p2[i]);
      p2[i] = NULL;
    }
  }
  if (p2 != NULL)
  {
    free(p2);
    p2 = NULL;
  }
}
int main()
{
  char **p2 = NULL;
  int num = 5;
  p2 = getMem(num);
  printf("排序前\n");
  printfMem(p2, num);
  sortMem(p2,num);
  printf("排序后\n");
  printfMem(p2, num);
  freeMem(p2, num);
  system("pause");
  return 0;
}

发现与第二种的输出函数相同~

最后修改:2019 年 02 月 27 日 02 : 33 PM
如果觉得我的文章对你有用,请随意赞赏