guy
guy

Reputation: 9

Accessing pointers in struct and getting segmentation fault

I am trying to access the objectName and questionName and I keep getting a segmentation fault. When I use a char array it only prints it the questionName not the objectName. I have allocated memory to everything so it must be to do with how I access these pointers. If someone could explain why I get a segmentation fault that would be great.

#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;
}

Upvotes: 0

Views: 67

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

You also need to malloc() the questionName, objectName and so on. But you can also do something easier and simlper, use strdup() like this

ptr->questionName = strdup("Does it have a tail?");

One more thing, you need to check the return value of malloc() against NULL.

NOTE: And please don't use spaces around the -> operator, it looks terrible. Also, be consistent with white space usage, use enough of it not too little but not too much. Only, be consistent with your own style.

Upvotes: 3

Related Questions