samedi 29 juillet 2017

segmentation fault (core dumped) pointer struct data type

i am trying to create a tree using struct in C

#include<stdio.h>
#include<stdlib.h>

struct node{
  int data;
  struct node * next, * left, * right;
};

struct node * createtree(int data){
  struct node * kosong = (struct node*)malloc(sizeof(struct node*));
  kosong->data = data;
  kosong->left = kosong->right = NULL;
  return kosong;
}

void printtree(struct node * tree){
  if(tree == NULL) return;
  printtree(tree->left);
  printf("%d ",tree->data);
  printtree(tree->right);
}

int main(){
  struct node * pohon = NULL;
  pohon = createtree(1);
  pohon->left = createtree(2);
  pohon->right = createtree(3);
  pohon->left->left = createtree(4);
  pohon->left->right = createtree(5);
  printtree(pohon);
}

whenever i compile it gets segmentation fault. Then i try to delete the * next pointer and it compiles & run successfully. I know tree does not need the * next pointer , but i dont see why it wont compile just because of another same pointer. Appreciate your help.

Aucun commentaire:

Enregistrer un commentaire