我在函数中调用strtok以便从逗号分隔的字符*中获取两个字符*。当我这样做时,它是段错误的,我不太确定为什么。
Tree tree = create_node(NULL);
add(tree, "jacob");
add(tree, "jacob, blue");
(添加方法的一部分):
void add(Tree tree, char * input){
printf("Add: %s\n", input);
char * parent_name;
char * child_name;
if(strstr(input, ",") != NULL){
const char delimiter[2] = ",";
parent_name = strtok(input, delimiter);
child_name = strtok(NULL, delimiter);
}else{
parent_name = input;
}
printf("pn, %s cn: %s\n", parent_name, child_name);
实际结果:
Add: jacob
pn, jacob cn: (null)
//Empty tree!
//jacob is the root
Add: jacob, blue
Segmentation fault (core dumped)
在第一个strtok()调用上出现段错误。我真的很困惑为什么。抱歉,这真的很基础。
答案 0 :(得分:0)
赞:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Tree {
} Tree;
void add(Tree *tree, const char *str)
{
char *input = strdup(str);
char *parent_name = NULL;
char *child_name = NULL;
printf("Add: %s\n", input);
if(strstr(input, ",") != NULL) {
const char delimiter[2] = ",";
parent_name = strtok(input, delimiter);
child_name = strtok(NULL, delimiter);
} else {
parent_name = input;
}
printf("pn, %s cn: %s\n", parent_name, child_name);
free(input);
}
Tree *create_node()
{
return NULL;
}
int main()
{
Tree *tree = create_node(NULL);
add(tree, "jacob");
add(tree, "jacob, blue");
return 0;
}