簡體   English   中英

在C中使用strtok分割字符串

[英]Splitting string with strtok in C

我不知道為什么第二個while循環沒有執行。 它對result [count] = atoi有訪問沖突。我想添加strcpy會有所幫助,因為我意識到原始字符串已被修改,但沒什么區別。 另外,我實際上是在使用C ++,但是大多數資源是在C中需要速度的地方。

int* split(const char* str, const char* delim)
{
    char* tok;
    int* result;
    int count = 0;

    char* oldstr = (char*)malloc(sizeof(str));
    strcpy(oldstr, str);

    tok = strtok((char*)str, delim);
    while (tok != NULL)
    {
        count++;
        tok = strtok(NULL, delim);
    }

    result = (int*)malloc(sizeof(int) * count);

    count = 0;
    tok = strtok((char*)oldstr, delim);
    while (tok != NULL)
    {
        result[count] = atoi(tok);
        count++;
        tok = strtok(NULL, delim);
    }
    return result;
}
    char* oldstr = (char*)malloc(sizeof(str));
    strcpy(oldstr, str);

您沒有分配足夠的空間。 由於strchar * ,因此您要在平台上分配char *占用的字節數,這可能不足以容納字符串。 你要:

    char* oldstr = malloc(strlen(str)+1);
    strcpy(oldstr, str);

或者,為簡單起見:

    char* oldstr = strdup(str);

暫無
暫無

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

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