我有一个链表并试图将其中一个值分成两个不同的变量。我从包含 "0000:c29302"
的 id 变量开始,但我想将 ":"
任一侧的部分拆分为 clientid
和 token 变量。
当我运行我的代码时,它进入了 split 函数中的 while 循环,但随后就崩溃了。谢谢!
typedef struct node {
char *id;
char *clientid;
char *token;
struct node * next;
} credentials;
void split(credentials * head, char *delim);
int main()
{
credentials * head = NULL;
head = malloc(sizeof(credentials));
head->id = "0000:c29302";
head->next = NULL;
split(head, ":");
}
void split(credentials * head, char *delim)
{
char *token;
char *temp;
credentials * current = head;
while (current != NULL) { //THIS WHILE LOOP
temp = current->id;
token = strtok(temp, delim);
while(token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, delim);
}
current = current->next;
}
}
最佳答案
发生这种情况是因为 strtok()
修改了字符串参数!由于您在这里使用的是字符串文字,因此它很可能保存在您平台上的只读内存中。因此,每次修改它的尝试都会导致“分段违规”。
如果您确定您的字符串是可修改的,例如通过使用
head->id = strdup("0000:c29302");
它应该按预期工作!
关于结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263749/