一个二级指针排序练习

2016-06-28  本文已影响58人  司马捷
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
int getMemory(char ***p,int num){
    int i = 0;
    char **tmp = NULL;
    if (p == NULL) {
        return -1;
    }
    tmp = (char **)malloc(sizeof(char *)*num);
    if (tmp == NULL) {
        return -2;
    }
    
    for (int i = 0; i<num; i++) {
        tmp[i] = (char*)malloc(sizeof(char) *100);
        sprintf(tmp[i], "%d",i+1);
    }
    *p = tmp;
    
    return i;
}

int freeMenmory(char ***p,int num){
    char **tmp = NULL;
    if (p == NULL) {
        return -1;
    }
    tmp = *p;
    for (int i = 0; i<num; i++) {
        free(tmp[i]);
    }
    free(tmp);
    *p = NULL;//把实参赋值成NULL
    
    return 0;
}
int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");

    char **p2 = NULL;//二级指针
    int num = 5;
    p2 = (char **)malloc(sizeof(char **)*num);
   // printf("char **---->%d",sizeof(long  **));// long long 指针变量占用的字节数也是8个字节.
    for (int i = 0; i<5; i++) {
        p2[i] = (char *)malloc(sizeof(char) *100);//这里是100个字节大小注意
        sprintf(p2[i], "%d%d%d",i+1,i+1,i+1);
    }
    /**
     *  排序之前
     */
    char *tmp;
    printf("排序之前\n");
    for (int i = 0; i<num; 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;
            }
        }
    }*/
    tmp = malloc(sizeof(char) *100);//要分配内存
    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;
                strcpy(tmp, p2[i]);
                strcpy(p2[i], p2[j]);
                strcpy(p2[j], tmp);
            }
        }
    }
    printf("排序之后\n");
    for (int i = 0; i<num; i++) {
        printf("%s\n",p2[i]);
    }
    
    //释放内存
    for(int i = 0;i<num;i++ ){
        if (p2[i] != NULL) {
            free(p2[i]);
            p2[i] = NULL;
        }
    }
    
    char ***p = malloc(100);
    getMemory(p, 10);
    for (int i = 0; i<10; i++) {
        printf("%s\n",p[i]);
    }
    
    
    return 0;
}

上一篇下一篇

猜你喜欢

热点阅读