Assignment from incompatible pointer type?

Jad Dava
Jad Dava used Ask the Experts™
on
This part of my program is giving me an incompatible pointer type warning on the fourth line:

void add(queue *q, int x)
{
    node_pointer temp;
    temp = (queue)malloc(sizeof(struct queuenode));
    temp -> data = x;
    temp -> next = NULL;

    if ((*q)==NULL)
    {
        (*q) -> front = temp;
        (*q) -> back = temp;
    }
    else
    {
        (*q) -> back -> next = temp;
        (*q) -> back = temp;
    }
}

Open in new window


These are the headers that include the type defs.

typedef struct queuenode {
    int data;
    struct queuenode *next;
} *node_pointer;

Open in new window


typedef struct endpointer {
    node_pointer front;
    node_pointer back;
} *queue;

Open in new window



The pseudo code reads:
Receives queue via pass by reference and data to be added via pass by value
Allocates memory for new queuenode structure and assigns it to temp (a queue)
sets the data portion equal to the item to be added
sets the next pointer to point to the NULL
the new node will always point to NULL.
   If the queue is empty
        set both front and back to this new node
  Otherwise
       attach it to to the next pointer of the back node
      move back pointer to this new node since it is now the last node in the queue
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
if temp is a 'node_pointer' you should do


temp = (node_pointer)malloc(sizeof(struct queuenode));

Open in new window


granted that the node_pointer was defined as 'struct queuenode *'.

generally i would prefer not to use alias type with ambiguous name but the original

struct queuenode * temp = NULL;
temp = (struct queuenode *)malloc(sizeof(struct queuenode));

Open in new window


Sara
Top Expert 2016
Commented:
it seems to me that the naming of your structures and typedef's and the mix up of structures and pointers to structures is likely to confuse you when writing code.

you definitively should avoid to use ambiguous and inconsistent names.

why not simply have

typedef struct node
{
     int data;
     struct node * next;
} node;

typedef struct queue
{
     node * front;
     node * back;
} queue;

Open in new window


the asterisk * much better tells that you were dealing with pointers as if you were using 'node_pointer' and 'queue' type where the first is pointer to struct 'queuenode' while the second is a pointer to struct 'end_pointer' what actually is not only a miserable naming but completely wrong.

Sara

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial