簡體   English   中英

C 拆分字符串 function

[英]C split string function

我正在嘗試實現 function 來拆分字符串,但我不斷遇到分段錯誤。 我正在研究 Windows XP,因此我還必須實現 strdup(),因為 Windows API 不提供它。 誰能告訴我以下代碼有什么問題。

char** strspl(char* str, char* del)
{
    int size = 1;

    for(int i = 0; i < strlen(str);) {
        if(strncmp(str + i, del, strlen(del)) == 0) {
            size++;
            i += strlen(del);
        }
        else {
            i++;
        }
    }
    char** res = (char**)malloc(size * sizeof(char*));
    res[0] = strdup(strtok(str, del));
    for(int i = 0; res[i] != NULL; i++) {
        res[i] = strdup(strtok(NULL, del));
    }
    return res;
}

char* strdup(char* str) {
    char* res = (char*)malloc(strlen(str));
    strncpy(res, str, sizeof(str));
    return res;
}

編輯:使用我發現的調試器,該程序在以下行之后崩潰:

res[0] = strdup(strtok(str,del));

另外,我修復了 strdup(),但仍然沒有進展。

您沒有計算 null 終止符,並且您正在復制錯誤的字節數

char* strdup(char* str) {
    char* res = (char*)malloc(strlen(str)); /* what about the null terminator? */
    strncpy(res, str, sizeof(str)); /* sizeof(str)
                                    ** is the same as
                                    ** sizeof (char*) */
    return res;
}

您的strdup() function 不正確。 其中的sizeof(str)str指針的大小(可能是 4 或 8 個字節),而不是string 的長度 請改用提供的庫_strdup()

malloc不會將分配的 memory 初始化為\0 您是否嘗試過使用calloc代替? 我懷疑段錯誤是由於res[i] != NULL比較造成的。

這段代碼有很多問題,但主要缺陷是試圖實現這個 function。 它只會為您提供邊際收益(如果有的話)。

比較以下兩個代碼片段:

/* Using strtok... */
char *tok = strtok(str, del);
while (tok != NULL) {
    /* Do something with tok. */
    tok = strtok(NULL, del);
}

-

/* Using your function... */
char **res = strspl(str, del, &size);
size_t i;
for (i = 0; i < size; i++) {
    /* Do something with *(res + i). */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM