-7

i am using this code but it is not running. it is not running in Dev C++. it runs then blows up.

#include <iostream>
using namespace std;
struct Node
{
    struct Node* left;
    int data;
    struct Node* right;
};
typedef struct Node *node;
int main()
{
    node n;
    n->data = 4;
    cout << n->data << endl;
    return 0;
}
Amit
  • 105
  • 1
  • 6

2 Answers2

0

You need to allocate memory for n before using it, something like:

node n = new Node;
P.An
  • 355
  • 1
  • 9
  • Change allocate to initialise – Richard Critten Oct 03 '17 at 14:31
  • @StoryTeller If you exclude typedef, `n` would be a pointer to a structure of type Node, which is not allocated - you get a segmentation violation running it. Author should do something like: `node n = new Node;` – P.An Oct 03 '17 at 14:36
0

Clearly the n variable is just a pointer which points to who knows where. You need to assign it some memory address where it can read the data from or write to.
This should do the trick:

node n = new Node;

The typedef struct Node *node; might be a little confusing for you.
You can write:

Node* n = new Node;

And get rid off the typedef which is much more clear that the n is just a pointer and thus you need to assign it some address where it points to.

ProXicT
  • 1,903
  • 3
  • 22
  • 46