4

I have the following:

typedef struct Node_struct
{
    int number;
    Node *nextNode;
    Node *prevNode;
} Node;

and later

Node *nodeInSet = lookup(set, number);
nodeInSet->nextNode = (Node *) malloc(sizeof(Node));
nodeInSet->nextNode->prevNode

the last line is saying: "expression must have pointer-to-class type". I can't see how my code is wrong. Since nodeInSet->nextNode is a Node *, I think I should be allowed to write nodeInSet->nextNode->prevNode. What is not working here?

Utku
  • 2,025
  • 22
  • 42
  • I also suspect that you are using the wrong compiler otherwise [Do not cast the return value from `malloc()`](http://stackoverflow.com/a/605858/1983495). You are allowed to write that, but you really shouldn't. From the sample code it's not possible to say why is the error happening, can you post a reproducible sample? Also, wouldn't `nodeInSet->nextNode->prevNode` be `nodeInSet`? if the list is correctly populated. – Iharob Al Asimi May 17 '15 at 15:00
  • 1
    inside `Node_struct` the `typedef Node` is not yet defined, so you should declare `struct Node_struct *nextNode` – bolov May 17 '15 at 15:03
  • a struct definition should not be typedef'd. typedef'ing clutters the code, leads to mis-understandings, adds no value, and clutters the compiler name space. Rather always use: 'struct Node_struct' – user3629249 May 18 '15 at 15:38

2 Answers2

6

The prevNode and nextNode members have incomplete type, you have to write it like this

typedef struct Node_struct
{
    int number;
    struct Node_struct *nextNode;
    struct Node_struct *prevNode;
} Node;

or

typedef struct Node_struct Node;
struct Node_struct
{
    int number;
    Node *nextNode;
    Node *prevNode;
};

The reason is that you can declare a poniter to an incomplete type, but if you try to dereference the pointer, like when you use the -> operator, then the type must be known, because the size of the type is needed.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
3

You can change your code to this.

typedef struct Node_struct
{
    int number;
    struct Node_struct *nextNode;
    struct Node_struct *prevNode;
} Node;
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Rishitha Minol
  • 323
  • 2
  • 11