在堆上自己分配内存,改变的是指针的指向
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printMyArray33(char **myArray, int num)
{
int i = 0;
for (i = 0; i < num; i++)
{
//printf("%s \n",myArray[i]);
printf("%s \n", *(myArray + i));
}
}
void sortMyArray33(char **myArray, int num)
{
int i = 0, j = 0;
char *tmp = NULL;
//排序
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (strcmp(myArray[i], myArray[j]) < 0)
{
tmp = myArray[i];
myArray[i] = myArray[j];//注意 改变的是指针的指向
myArray[j] = tmp;
}
}
}
}
char **getnum()
{
int i = 0, j = 0;
int num = 5;
char **p2 = NULL;
p2 = (char **)malloc(sizeof(char *)* num);
if (p2==NULL)
{
return NULL;
}
for (i = 0; i < 5; i++)
{
p2[i] = (char *)malloc(sizeof(char) * 100);//char buf[100]
sprintf(p2[i], "%d%d%d", i + 1, i + 1, i + 1);
}
return p2;
}
void getnum_free(char **p2,int num)
{
int i = 0;
//释放内存
for (i = 0; i < num; i++)
{
if (p2[i] != NULL)
{
free(p2[i]);
p2[i] = NULL;
}
}
}
void main()
{
int i = 0, j = 0;
char **p2 = NULL;
int num = 5;
char *tmp = NULL;
char tmpbuf[100];
p2 = (char **)malloc(sizeof(char *)* num);
for (i = 0; i < 5; i++)
{
p2[i] = (char *)malloc(sizeof(char) * 100);//char buf[100]
sprintf(p2[i], "%d%d%d", i + 1, i + 1, i + 1);
}
printf("排序之前\n");
printMyArray33(p2, num);
printf("排序之后\n");
sortMyArray33(p2, num);
for (i = 0; i < num; i++)
{
printf("%s \n", p2[i]);
}
getnum_free(p2,num);
printf("hello... \n");
}
int main02()
{
int i = 0,j=0;
char **p2 = NULL;
int num = 5;
char *tmp = NULL;
char tmpbuf[100];
p2 = (char **)malloc(sizeof(char *)* num);
for (i=0;i<5;i++)
{
p2[i] = (char *)malloc(sizeof(char) * 100);//char buf[100]
sprintf(p2[i], "%d%d%d", i + 1, i + 1, i + 1);
}
printf("排序之前\n");
for (i=0;i<num;i++)
{
printf("%s \n", p2[i]);
}
排序 交换的是指针
//for (i=0;i<num;i++)
//{
// for (j=i+1;j<num;j++)
// {
// if (strcmp(p2[i],p2[j])<0)
// {
// tmp = p2[i];
// p2[i] = p2[j];
// p2[j] = tmp;
// }
// }
//}
//排序 交换的是内存
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (strcmp(p2[i], p2[j]) < 0)
{
strcpy(tmpbuf, p2[i]);
strcpy(p2[i], p2[j]);
strcpy(p2[j], tmpbuf);
}
}
}
printf("排序之后\n");
for (i = 0; i < num; i++)
{
printf("%s \n", p2[i]);
}
//释放内存
for (i=0;i<num;i++)
{
if (p2[i] != NULL)
{
free(p2[i]);
p2[i] = NULL;
}
}
printf("hello... \n");
return 0;
}