【发布时间】:2019-12-03 06:18:30
【问题描述】:
我正在尝试通过空格和制表符对字符串进行标记。但是,当我运行我的程序时,我在尝试打印令牌时收到分段错误错误。我不明白为什么会发生这种情况,因为无论我使用token 还是使用*token 尊重令牌,打印语句都不起作用。以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char string = "String1 String2 String3";
char *token = strtok(string," \t"); /* The atomic weights and names are separated by either a space or tab */
while (token != NULL) /* While there is still content for us to read */
{
printf("token = %s\n", *token);
token = strtok(NULL, " \t");
}
exit(1);
}
【问题讨论】:
-
char string =应该是char string[] = -
打开编译器警告——如果你允许编译器会指出一些非常明显的问题。
-
您将
string声明为char而不是char[]。由于有点神秘的原因,这不是错误,但至少应该发出警告。 -
始终检查编译器的警告!对于
gcc,我使用gcc -Wall -Wextra -pedantic。 -
另外,您为什么决定在打印时取消引用
token?