c - 为什么 strtok_r 总是找到模式 "."?

标签 c strtok

在我的系统上,以下程序:

int main(){
        char *strgptr;
        char buf[5] = {'b','a','a','a','\0'};
        char *tmp = strtok_r(buf, ".", &strgptr);
        if(tmp != NULL){
                printf("Found a . in baaa?\n");
                printf("It was found starting at: %s\n", tmp);
        }
        else
                printf("Everything is working.\n");
}

打印:

Found a . in baaa?
It was found starting at: baaa

但是,如果我交换“.” strtok_r 中“a”的分隔符字符串,我得到(如预期的那样):

Found a . in baaa?
It was found starting at: b

但是交换“.”对于没有出现在 buf 中的任何其他字符(例如“c”)产生:

Found a . in baaa?
It was found starting at: baaa

正如预期的那样,strtok_r 的手册页说:

The strtok() and strtok_r() functions return a pointer to the next token, 
or NULL if there are no more tokens.

那么,为什么当传递的字符串不包含任何相关标记时,strtok_r 无法返回 NULL?

最佳答案

因为没有找到定界符,所以你将返回整个字符串。它的作用就好像字符串后有一个不可见的定界符。

关于c - 为什么 strtok_r 总是找到模式 "."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13454201/

相关文章:

C - 根据值移动或删除多个节点

c - c代码中fseek行的段错误

C - scanf 不会停止在字符串输入中循环

C - 尝试在 linux 中构建一个简单的 shell 并在循环中使用 strtok、realloc 时遇到问题

PHP字符串函数获取数组字符串值中字符串的特定行

c - 将数组中的位存储为整数

c - 提供特定值但返回错误指针

c - 如何从指针获取字符串值

c - 交换 "C"中句子中的单词

c - C 中的 strtok 和 (null)