标签:length pause ++ style 函数 分配 sort har des
头文件:
#include<stdlib.h> #include<stdio.h> #include<string.h>
函数原型:
char ** createBuff(char **buff, int arraylength, int charLength); //创建二级指针 void initDemo(char **buff, int arrayLength); //初始化二级指针 void destoryBuff(char **buff, int arrayLength); //销毁二级指针 void printBuff(char ** buff, int arrayLength); //遍历二级指针 void sortBuffArray(char ** buff, int arrayLength); //排序
实现函数:
1 char ** createBuff(char **buff, int arrayLength, int charLength){ 2 3 int i; 4 5 buff = (char **)malloc(sizeof(char *) * arrayLength); //给*buff分配空间,buff指向它的首地址 6 7 for (i = 0; i < arrayLength; ++i){ 8 9 buff[i] = (char *)malloc(sizeof(char) * charLength); //*buff[i]分配空间,buff[i]指向它的首地址 10 11 } 12 13 return buff; 14 } 15 16 void initDemo(char **buff, int arrayLength){ 17 18 int i; 19 20 for (i = 0; i < arrayLength; ++i){ 21 22 sprintf(buff[i], "%d%d%d", i + 1 , i + 1, i + 1); 23 24 } 25 } 26 27 void destoryBuff(char **buff, int arrayLength){ 28 29 int i; 30 31 for (i = 0; i < arrayLength; ++i){ 32 33 if(buff[i] != NULL){ 34 35 free(buff[i]); 36 37 buff[i] = NULL; 38 39 } 40 41 } 42 43 if(buff != NULL){ 44 45 free(buff); 46 47 buff = NULL; 48 49 } 50 } 51 52 53 54 void printBuff(char ** buff, int arrayLength){ 55 56 int i ; 57 58 for (i = 0; i < arrayLength; ++i){ 59 printf("%s\n", buff[i]); 60 } 61 } 62 63 void sortBuffArray(char ** buff, int arrayLength){ 64 65 int i, j; 66 67 char *temp = NULL; 68 69 for( i = 0; i < arrayLength; ++i){ 70 71 for(j = i + 1; j < arrayLength; ++j){ 72 73 if(strcmp(buff[j], buff[i]) > 0){ 74 75 temp = buff[i]; 76 77 buff[i] = buff[j]; 78 79 buff[j] = temp; 80 81 } 82 83 } 84 85 } 86 87 }
测试:
void main(){ int arrayLength = 5, charLength = 100; char **buff = NULL; buff = createBuff(buff, arrayLength, charLength); initDemo(buff, arrayLength); printf("排序前\n"); printBuff(buff, arrayLength); sortBuffArray(buff, arrayLength); printf("排序后\n"); printArray(buff, arrayLength); destoryBuff(buff, arrayLength); system("pause"); }
注意:
char **buff 变量不能当作实参传入到createBuff函数中的形参,以为createBuff函数调用结束会释放掉形参buff ,因此只能当作返回值返回或者,函数中定义三级指针,调用时传入buff的地址即可。
标签:length pause ++ style 函数 分配 sort har des
原文地址:http://www.cnblogs.com/zhouquan-1992-04-06/p/6207381.html