objectNameとquestionNameにアクセスしようとしていますが、セグメンテーションフォルトが発生し続けます。私がchar配列を使うと、objectNameではなくquestionNameだけが出力されます。私はすべてにメモリを割り当てたので、どのようにこれらのポインタにアクセスする必要があります。なぜ誰かが私が偉大なセグメンテーション違反を得る理由を説明することができれば。構造体のポインタにアクセスしてセグメンテーションフォールトを取得しています
#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