[英]C Programming: strtok delivers segmentation fault
我正在嘗試通過空格和制表符來標記字符串。 但是,當我運行我的程序時,當我嘗試打印令牌時,我收到了 Segmentation Fault 錯誤。 我不明白為什么會發生這種情況,因為無論我使用token
還是我使用*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
或char string[]
。 您正在嘗試將整個字符串分配給單個char
。
其次,字符串文字是只讀數據,但strtok()
修改它給定的char
緩沖區。 所以你的代碼有未定義的行為,因為它試圖修改只讀內存。
如果將char string
更改為char string[]
,則字符串文字數據將在運行時復制到可寫緩沖區中。 然后在調用printf()
時將*token
更改為token
,因為%s
需要一個char*
指針,而不是單個char
。 然后您的代碼將按預期工作:
#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);
return 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.