我试图理解为什么下面的代码片段给出了分段错误:
void tokenize(char* line)
{
char* cmd = strtok(line," ");
while (cmd != NULL)
{
printf ("%s\n",cmd);
cmd = strtok(NULL, " ");
}
}
int main(void)
{
tokenize("this is a test");
}
Run Code Online (Sandbox Code Playgroud)
我知道strtok()实际上并没有对字符串文字进行标记,但在这种情况下,line直接指向"this is a test"内部为数组的字符串char.是否有任何令牌化line而不将其复制到数组中?
我有两个辅助函数来分解十进制价格格式的字符串,即."23.00","2.30"
考虑一下:
char price[4] = "2.20";
unsigned getDollars(char *price)
{
return atoi(strtok(price, "."));
}
unsigned getCents(char *price)
{
strtok(price, ".");
return atoi(strtok(NULL, "."));
}
Run Code Online (Sandbox Code Playgroud)
现在,当我运行以下时,我得到一个分段错误:
printf("%u\n", getDollars(string));
printf("%u\n", getCents(string));
Run Code Online (Sandbox Code Playgroud)
然而,当我单独运行它们而没有一个跟随另一个时,它们工作正常.我在这里错过了什么?我必须做某种重置strtok ??
我的解决方案
根据我在下面选择的答案中获得的关于strtok的知识,我更改了辅助函数的实现,以便它们首先复制传入的字符串,从而屏蔽原始字符串并防止出现此问题:
#define MAX_PRICE_LEN 5 /* Assumes no prices goes over 99.99 */
unsigned getDollars(char *price)
{
/* Copy the string to prevent strtok from changing the original */
char copy[MAX_PRICE_LEN];
char tok[MAX_PRICE_LEN];
/* Create a copy of the original string */
strcpy(copy, price);
strcpy(tok, strtok(copy, "."));
/* Return …Run Code Online (Sandbox Code Playgroud) 出于某种原因,我在第一次使用strtok()时得到一个异常我想要完成的是一个函数,它只是检查子串在字符串中是否重复.但到目前为止我还没有开始工作
int CheckDoubleInput(char* input){
char* word = NULL;
char cutBy[] = ",_";
word = strtok(input, cutBy); <--- **error line**
/* walk through other tokens */
while (word != NULL)
{
printf(" %s\n", word);
word = strtok(NULL, cutBy);
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
和主要调用功能:
CheckDoubleInput("asdlakm,_asdasd,_sdasd,asdas_sas");
Run Code Online (Sandbox Code Playgroud)

为什么下面的代码给出了Seg.最后一行出错?
char* m=ReadName();
printf("\nRead String %s\n",m); // Writes OK
char* token;
token=strtok(m,'-');
Run Code Online (Sandbox Code Playgroud)
如上所述,读取字符串打印没有问题,但为什么不能拆分为令牌?
我有以下代码:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[] = "John|Doe|Melbourne|6270|AU";
char fname[32], lname[32], city[32], zip[32], country[32];
char *oldstr = str;
strcpy(fname, strtok(str, "|"));
strcpy(lname, strtok(NULL, "|"));
strcpy(city, strtok(NULL, "|"));
strcpy(zip, strtok(NULL, "|"));
strcpy(country, strtok(NULL, "|"));
printf("Firstname: %s\n", fname);
printf("Lastname: %s\n", lname);
printf("City: %s\n", city);
printf("Zip: %s\n", zip);
printf("Country: %s\n", country);
printf("STR: %s\n", str);
printf("OLDSTR: %s\n", oldstr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
执行输出:
$ ./str
Firstname: John
Lastname: Doe
City: Melbourne
Zip: 6270
Country: AU
STR: John
OLDSTR: John
Run Code Online (Sandbox Code Playgroud)
为什么我不能保留旧数据,也不能保留, …
可能重复:
strtok给出分段错误
为什么我使用此代码获得段错误?
void test(char *data)
{
char *pch;
pch = strtok(data, " ,.-"); // segfault
while (pch != NULL)
{
printf("%s\n", pch);
pch = strtok(NULL, " ,.-");
}
return NULL;
}
char *data = "- This, a sample string.";
test(data);
Run Code Online (Sandbox Code Playgroud)