-3

I am writing a queue implementation program(in c) that has 2 node variables, front and rear. I declared them as follows,

struct queue
{
    NODE* front, rear;
    int size;
};

Upon compilation, I get the following error,

error: incompatible types when assigning to type ‘NODE’ {aka ‘struct node’} from type ‘void *’.

queue->rear = NULL;

For some reason it identifies rear to be of NODE type instead of NODE*

The code works fine when 'front' and 'rear' are declared separately as follows:

struct queue
{
    NODE* front;
    NODE* rear;
    int size;
};

How do I declare multiple variables in a single line in a structure(in c)?

Akshxy X
  • 1
  • 1
  • 2
    Read your code carefully: in `NODE* front, rear;` what is the type of `rear`? – G.M. Dec 06 '21 at 11:42
  • 2
    This is similar to https://stackoverflow.com/questions/13618282/declaring-multiple-object-pointers-on-one-line-causes-compiler-error – doctorlove Dec 06 '21 at 11:43
  • 1
    Note that the asterisk applies to the thing at the right from it, not to the left of it. So you should read `Node * front` as `Node (*front)` instead of `(Node*) front`. For this reason I personally prefer a space between the type and the asterisk and many styleguides recommend to define only one variable on each line. – wovano Dec 06 '21 at 12:05
  • 1
    Congratulations, you have just found the main reason why you should never declare them on the same line. – Lundin Dec 06 '21 at 12:21

1 Answers1

0
NODE* front, rear;

is equivalent of

NODE* front;
NODE rear;

So it's no surprise than doing queue->rear = NULL; is invalid.

The proper declaration is

NODE *front, *rear;

but I heavely suggest that you don't do multiple declaration in one line for the reason that you migth confuse what is a pointer or not (it's why you created this topic).

I suggest

NODE *front;
NODE *rear;
Tom's
  • 2,448
  • 10
  • 22