c - strtok() 返回奇怪的值和段错误

标签 c strtok

我正在使用 strtok() 从文件中获取的数据中提取字符。

这是我的代码:

fgets(text, 12, myFile);

printf ("text is: %s \n", &text);
char *token;
token = strtok(text, " ");
printf("first token is: %s \n", &token);

printf ("text is: %s \n", &text);
token = strtok(NULL, " ");
printf("second token is: %s \n", &token);

输出如下:

text is: 4 3       //this is the expected and correct value of "text"
first token is:  ڱ[? 
text is: 4        // I was expecting this to be 3 after getting the first token...
second token is: "ڱ[? 
Segmentation fault: 11

如您所见,strtok() 不仅没有得到正确的值,而且似乎以一种非常奇怪的顺序遍历了文本。关于为什么会这样的任何想法?非常感谢您!

最佳答案

所有这些 printf 中的 %s 需要一个 char*。您传递 &text&token,它们都是 char**。这会调用 C11 标准中规定的未定义行为:

7.21.6.1 The fprintf function

[...]

  1. If a conversion specification is invalid, the behavior is undefined. 282 If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

要解决此问题,请从所有这些 printf 中删除与号,即替换以下所有语句:

printf ("text is: %s \n", &text);
printf("first token is: %s \n", &token);
printf ("text is: %s \n", &text);
printf("second token is: %s \n", &token);

printf ("text is: %s \n", text);
printf("first token is: %s \n", token);
printf ("text is: %s \n", text);
printf("second token is: %s \n", token);

关于c - strtok() 返回奇怪的值和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447873/

相关文章:

c - 重用 strtok 为 null

c++ - 调用 strtok() 时发生访问冲突; C++

c# - 我想读取控制台模式子进程的输出

c - 没有参数的格式说明符

c - 使用 strtok 分割 c 数组

c++ - strtok_s 未在此范围内声明

c - 不兼容的指针不允许将 csv 放置到二维数组中

c++ - 如何将 gdb 用于多线程网络程序

python - 如何正确处理 C 中的文件读/写错误?

python - setup.py 找不到 numpy header