1 #define _CRT_SECURE_NO_WARNINGS 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 6 //產生malloc 7 char **getMem41(int num) 8 { 9 char **p2 = NULL; 10 int i = 0; 11 12 p2 = (char **)malloc(sizeof(char*)* num); 13 if (p2 == NULL) 14 { 15 return NULL; 16 } 17 for (i = 0; i < num; i++) 18 { 19 p2[i] = (char *)malloc(sizeof(char)* 100); //char buf[100]; 20 sprintf(p2[i], "%d%d%d", i + 1, i + 1, i + 1); //按照這種格式("%d%d%d",i+1,i+1,i+1)打印到p2[i]; 21 } 22 return p2; 23 } 24 25 //排序 26 void sortNum31(char **array, int num) 27 { 28 char *tmp = NULL; 29 int i = 0, j = 0; 30 for (i = 0; i < num; i++) 31 { 32 for (j = i; j < num; j++) 33 { 34 if (strcmp(array[i], array[j])<0) 35 { 36 tmp = array[i]; //注意:交換的數據的值,交換的是指針 //改變的是指針的指向 37 array[i] = array[j]; 38 array[j] = tmp; 39 } 40 } 41 } 42 } 43 44 //打印 45 46 void printNum31(char **array, int num) 47 { 48 int i = 0; 49 for (i = 0; i < num; i++) 50 { 51 printf("%s ", array[i]); 52 } 53 } 54 55 void getMem41_Free(char **p,int num) 56 { 57 int i = 0; 58 char **p2 = p; 59 for (i = 0; i < num; i++) 60 { 61 if (p2[i] != NULL) 62 { 63 free(p2[i]); 64 p2[i] = NULL; 65 } 66 } 67 if (p2 != NULL) 68 { 69 free(p2); 70 p2 = NULL; 71 } 72 } 73 74 int main() 75 { 76 int i = 0; 77 char **p2; 78 int num = 5; 79 char *tmp =NULL; 80 char tmpBuf[100]; 81 82 p2 = getMem41(num); 83 84 //排序之前打印 85 printf("排序前:\n"); 86 /*for (i = 0; i < num;i++) 87 { 88 printf("%s\n",p2[i]); 89 }*/ 90 printNum31(p2,num); 91 92 93 //排序 //交換的是指針 94 /*for (i = 0; i < num;i++) 95 { 96 for (int j = i + 1; j < num;j++) 97 { 98 if (strcmp(p2[i],p2[j])<0) 99 { 100 tmp = p2[i]; 101 p2[i] = p2[j]; 102 p2[j] = tmp; 103 } 104 } 105 }*/ 106 107 108 //排序 //交換的是內存 109 /*for (i = 0; i < num; i++) 110 { 111 for (int j = i + 1; j < num; j++) 112 { 113 if (strcmp(p2[i], p2[j]) < 0) 114 { 115 strcpy(tmpBuf, p2[i]); 116 strcpy(p2[i], p2[j]); 117 strcpy(p2[j], tmpBuf); 118 } 119 } 120 }*/ 121 122 //排序 123 sortNum31(p2, num); 124 //排序後 125 printf("\n排序後:\n"); 126 /*for (i = 0; i < num; i++) 127 { 128 printf("%s\n", p2[i]); 129 }*/ 130 printNum31(p2, num); 131 //釋放內存 132 getMem41_Free(p2, num); 133 system("pause"); 134 return 0; 135 }