一个练习分割字符串,二级指针分配内存

2016-06-28  本文已影响85人  司马捷
#include <stdio.h>
#include "string.h"
#include "stdlib.h"
///自己封装的拷贝字符串的方法
int ericCopy(char *to,char *from,long num){
    int ret = 0;
    if (from == NULL||to==NULL||num ==0) {
        return -1;
    }
    for (int i = 0; strlen(from); i++) {
        if (i<num) {
            to[i] = from[i];
        }else{
            to[i] = '\0';
            break;
        }
    }
    
    return ret;
    
}
int spitString(char *string,char spit,char **buff,int *count){
    int ret = 0;
    int temCount =0;
    if (string ==NULL||buff==NULL||count==NULL) {
        return -1;
    }
    char *p = string;
    char *ptmp = string;//临时指针
    do {
        p = strchr(ptmp, spit);
        if (p == NULL) {
            ret = -2;
            break;
        }
        //strncpy(buff[temCount], p, p-ptmp);
        ericCopy(buff[temCount], ptmp, p-ptmp);
        buff[temCount][p-ptmp] = '\0';
//        printf("%s",buff[temCount]);
        temCount++;
        ptmp = p = p+1;
    } while (*p!='\0');
    *count = temCount;
    return ret;
}

void freeMemory(char **p,int num){
    if (p == NULL) {
        return;
    }
    for (int i = 0; i<num; i++) {
        free(p[i]);
    }
    p = NULL;//把实参赋值成NULL

}

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");
    
//    char **buff = {"adf","ewr","asgaggd","wtew","dsgdsag"};
    char *buff = "adfadf,sdggd,sdf,erer,erer,";
    int count = -1;
//    char array[10][30];
    char **array = NULL;//这里使用动态分配内存的方法
    array = (char**)malloc(10*sizeof(char *));
    for (int i = 0; i<10; i++) {
        array[i] = (char *)malloc(30*sizeof(char));
    }
    printf("%s",array[2]);
    spitString(buff, ',', array, &count);
    printf("%p",array);
    
    if (count!=0) {
        for (int i = 0; i<count; i++) {
            printf("\n%s",array[i]);
        }
        printf("\n");
    }
    //free(array);
    freeMemory(array, count);//释放内存
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读