热门搜索 :
考研考公
您的当前位置:首页正文

二级指针的应用

来源:东饰资讯网
题目:字符串的拆分,有字符串"aasa,asd,sad,",按照','拆分
  • 方案一:在栈中创建一个数组,接收拆分后的结果
 /*
    src:要拆分的字符串
    split:拆分依据
    dst:拆分后存放的位置
    num:拆分字符串的个数
 */
int split_string1(IN const char *src, IN char *split,OUT char (*dst)[100], OUT int *num){

    if (src == NULL || split == NULL || dst == NULL || num == NULL ) {
        return -1;
    }
    
    int index = 0;
    const char *p  = src;
    const char *q  = src;
    while ((p = strchr(p, *split)) != NULL) {
        
        strncpy(*(dst +index), q, p - q);
        p = p + 1;
        q = p;
        index++;
    }
    
    if (*q != '\0') {
        strcpy(*(dst + index++), q);
    }
    
    *num = index;
    return  0;
}

  • 方案二:在栈中创建一个数组,接收拆分后的结果
//在堆区创建数组
int split_string2(IN const char *src, IN char *split,OUT char ***dst, OUT int *num){

    int flag = 0;
    
    if (src == NULL || split == NULL || dst == NULL || num == NULL ) {
        
        flag =  -1;
    }
    
    //先计算num
    const char *p = src;
    int index = 0;
    while ((p = strchr(p, *split)) != NULL) {
        
        index ++;
        p = p +1;
    }
    
    if (*(src + strlen(src) - 1) != *split) {
        
        index++;
    }
  
    *num = index;
    //开辟堆数组
    *dst = calloc(index, sizeof(char*));
    if (*dst == NULL) {
        
        fprintf(stderr, "开辟内存错误");
        flag =  -1;
    }
    
    const char *q = src;
    p = src;
    index = 0;
    while ((p = strchr(p, *split))) {
        //后面有一个 '\0'
        *(*dst + index)  = calloc( p -q + 1, sizeof(char));
        
        if (*(*dst + index) == NULL) {
            
            fprintf(stderr, "开辟内存错误");
            flag =  -1;
            goto END;
        }
        
        strncpy(*(*dst + index++), q, p - q);
        p = p + 1;
        q = p;
    }
    
    if (*q != '\0') {
        //后面有一个 '\0'
        *(*dst + index)  = calloc( strlen(q) + 1, sizeof(char));
        
        if (*(*dst + index) == NULL) {
            
            fprintf(stderr, "开辟内存错误");
            flag =  -1;
            goto END;
        }
        strcpy(*(*dst + index++), q);
    }
    
END:
    if (flag == -1) {
        free_two_point(dst, *num);
    }
    
    return flag;
}

注意:使用后要释放内存

int free_two_point(char ***p, int num){
    
    if (p == NULL) {
        return  -1;
    }

    for (int i = 0; i < num; i++) {
        
        if ((*p)[i] != NULL) {
            free((*p)[i]);
        }
    }
    
    *p = NULL;
    return  0;
}

Top