我想访问objectName和questionName,并且不断收到分段错误。当我使用char数组时,它只打印questionName而不是objectName。我已经将内存分配给了一切,所以它必须与我如何访问这些指针有关。如果有人能解释为什么我会得到一个很好的分段错误。访问结构中的指针并获取分段错误
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
char *objectName;
char *questionName;
struct node *left_ptr;
struct node *right_ptr;
};
void treePrint(struct node *ptr)
{
if (ptr == NULL)
{
return;
}
else
{
if (ptr -> questionName != NULL)//ptr is a question
{
printf("question: %s\n", ptr -> questionName);
//now print the yes and no subtrees:
treePrint(ptr->left_ptr);
treePrint(ptr->right_ptr);
}
else
{ // ptr is an object
printf("object: %s\n", ptr -> objectName);
}
}
}
int main(int argc, char const *argv[])
{
struct node *firstquestion = malloc(sizeof(struct node));
struct node *secondquestion = malloc(sizeof(struct node));
struct node *firstObject = malloc(sizeof(struct node));
struct node *secondObject = malloc(sizeof(struct node));
struct node *thirdObject = malloc(sizeof(struct node));
strcpy(firstquestion -> questionName, "Does it have a tail?");
strcpy(secondquestion -> questionName, "Is it round and edible?");
strcpy(firstObject -> objectName, "A pangolin");
strcpy(secondObject -> objectName, "Mandeep");
strcpy(thirdObject -> objectName, "Orange");
firstquestion -> left_ptr = firstObject;
firstquestion -> right_ptr = secondquestion;
secondquestion -> left_ptr = thirdObject;
secondquestion -> right_ptr = secondObject;
treePrint(firstquestion);
return 0;
}
你没有为'firstquestion-> questionName'分配内存,因此'strcpy(firstquestion - > questionName,“它是否有尾部?”);'是未定义的行为。 – EOF