2016-12-07 5 views
1

でここでは、私のコードです:バスエラー:私はコード、常にバスエラー10を実行しているときに10はstrtokとC

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; 
} 

私を助けてください!

+0

(http://stackoverflow.com/questions/4480552/why-does-the-following-c-program-give- a-bus-error) – Darthfett

+0

また、上記のコードでは、 'for'行の ';'の前に ')'がありません。 (そしておそらく '{'、 '}') – Toby

答えて

1

strtokは、それが渡されたバッファを変更します。これはcontractual次のとおりです。

Be cautious when using these functions. If you do use them, note that:

* These functions modify their first argument.

* These functions cannot be used on constant strings.

あなたがCでchar *str = "blah blah";として文字列を宣言すると、あなたはstrtokにそれを渡すときstrtokがバッファを変更したいので、その結果は定義されていない、それは読み取り専用にするメモリーを宣言しています読み取り専用なのでできません。この問題に対処するには

ではなく配列としてstrを宣言します。[参照] char str[] = "blah blah";

4

文字列定数を変更することはできません。 lineをこのように定義します。

char line[] = "test test test"; 
関連する問題