strtok注意事項

問題

最近使用strtok函數分割字符串,代碼異常退出,報段錯誤。
錯誤代碼如下

#include "string.h"
#include <stdio.h>

int main(){
    char *a = "ni hao wos s sd"; // 錯誤做法
    // char a[] = "ni hao wos s sd"; // 正確做法
    char *b = strtok(a," ");
    while(b != NULL){
        printf("TOKEN:%s",b);
        b = strtok(NULL, " ");
    }
    return 0;
}

如果 a變量是一個char * 時,會報錯,而將a改成數組,就不會報錯。

原因是 strtok 會修改參數,使用gdb調試,可以看到strtok會在原始字符中插入’\0’。

(gdb) p a
$5 = "ni\000hao\000wos s sd"

char *a = “ni hao wos s sd”; 指向常量,不能修改。
而 char a[] = “ni hao wos s sd”; 是將字符常量拷貝到棧裏面,是可以修改內容的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章