一個(gè)練習(xí)分割字符串,二級(jí)指針分配內(nèi)存

#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;//臨時(shí)指針
    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;//把實(shí)參賦值成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;//這里使用動(dòng)態(tài)分配內(nèi)存的方法
    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);//釋放內(nèi)存
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容