结构问题

标签 c linked-list strtok

我有一个链表并试图将其中一个值分成两个不同的变量。我从包含 "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/

相关文章:

c - 将节点移动到链表函数的末尾问题

c - 从 C 中的 txt 文件中读取和拆分未定义的字符串

c++ - 读取文件时如何将字符串转换为字符数组?

c - 初始化包含文件的结构

c++ - 如何让Makefile在一个目录下编译多个c文件和h文件

c - -> 和点有什么区别

c - 链接列表的访问冲突错误

c - 如何在 c 中制作二进制文件 ---- struct within a struct

c - 为什么在我的代码运行后进程被终止?处理返回 255

c - 琴弦不能正常工作