簡體   English   中英

總線錯誤:C中strtok為10

[英]Bus Error:10 with strtok in C

這是我的代碼,當我運行代碼時,總是出現總線錯誤10:

void print_tokens(char *line)
{
    static char whitespace[] = " \t\f\r\v\n";
    char *token;

    for(token = strtok(line, whitespace);
       token != NULL;
       token = strtok(NULL, whitespace))
       printf("Next token is %s\n", token);
}

int main(void)
{
    char *line = "test test test";
    print_tokens(line);
    return 0;
}

請幫我!

您不能修改字符串常量。 以這種方式定義line

char line[] = "test test test";

strtok將修改它傳遞的緩沖區; 這是合同規定的

使用這些功能時要小心。 如果確實使用它們,請注意:

*這些函數修改了它們的第一個參數。

*這些函數不能在常量字符串上使用。

當您將字符串聲明為char *str = "blah blah"; 在C語言中,您將其聲明為只讀內存,因此當您將其傳遞給strtok ,結果是不確定的,因為strtok要修改緩沖區,但不能,因為它是只讀的。

為了解決這個問題,請將str聲明為數組: char str[] = "blah blah";

暫無
暫無

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

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