/*** point_practice.c ***/ #include<stdio.h> #include<string.h> #include<stdlib.h> int sort( char **myp1 /*in*/, int num1, char (*myp2)[30], int num2, char ***myp3, int *num3) { int i = 0, j = 0, k = 0; int tmplen; char **p3 = NULL; char *tmpP = NULL; p3 = (char **)malloc((num1 + num2) * sizeof(char *)); if (NULL == p3) { return -1; } for (i = 0; i < num1; i++) { tmplen = strlen(myp1[i]) + 1; p3[i] = (char *)malloc(tmplen * sizeof(char)); if(NULL == p3[i]) { return -2; } strcpy(p3[i],myp1[i]); } for (j = 0; j < num2; j++,i++) { tmplen = strlen(myp2[j]) + 1; p3[i] = (char *)malloc(tmplen * sizeof(char)); if (NULL == p3[i]) { return -3; } strcpy(p3[i], myp2[j]); } tmplen = num1 + num2; for (i = 0; i < tmplen; i++) { for (j = i + 1; j < tmplen; j++) { if (strcmp(p3[i], p3[j]) > 0) { tmpP = p3[i]; p3[i] = p3[j]; p3[j] = tmpP; } } } *num3 = tmplen; *myp3 = p3; return 0; } void sortFree(char **p, int len) { int i; if (NULL == p) { return ; } for (i = 0; i < len; i++) { free(p[i]); } free(p); } /* 把二级指针指向二维内存释放掉 同时间接修改实参的地址 */ void sortFree01(char ***myp, int len) { int i = 0; char **p = NULL; if (myp == NULL) { return ; } p = *myp; if (p == NULL) { return; } for (i = 0; i < len; i++) { free(p[i]); } free(p); *myp = NULL; //间接赋值是指针最大的意义 } int main() { int ret; int i; char *p1[] = {"aaaaaa","cccccc","bbbbbb"}; char buf2[10][30] = {"11111","3333333","222222"}; char **p3 = NULL; int len1,len2,len3; len1 = sizeof(p1)/sizeof(*p1); len2 = 3; ret = sort(p1, len1, buf2, len2, &p3, &len3); if (0 != ret) { printf("func sort() err:%d\n",ret); return ret; } for (i = 0; i < len3 ;i++) { printf("%s\n",p3[i]); } return 0; }
原文地址:https://www.cnblogs.com/wanghao-boke/p/11827795.html
时间: 2024-10-26 05:43:25