captain monk
captain monk

Reputation: 727

Pointers and struct

This is my problem...i've got this code(creating a list)

typedef struct node
{
    int pid;
    int runtime;
    struct node *next;
}job;

int main()
//code
job *first = NULL;
job *last = NULL;
job *newnode;
//code
//from here
if( first == NULL )
{
     first = last = newnode;
     newnode->next = NULL;
}
else
{
     last->next = newnode;
     last = last->next;
}
// to here

So i wanted to do the part between from here to here in a function(so it would look better) And i did this..i created a function

void funct(job ** pfirst, job **plast, job*newnode);

in main instead of the strong part i use:

 funct(&first, &last, newnode);

and the function was like this

void funct(job ** pfirst, job **plast, job*newnode)
{
   if(*pfirst == NULL)
   {
      *pfirst = *plast = newnode;
       newnode->next = NULL;
   }
   else
   {
      *plast->next = newnode;//<----
      *plast = *plast->next;//<----
   }
}

The error is in the arrow and sais not part of a struct..

Upvotes: 3

Views: 187

Answers (2)

rahul maindargi
rahul maindargi

Reputation: 5615

In addition to solutions mentioned here your 2nd code has logical error.. you should be checking for if(*pfirst == NULL) and not if(*pfirst != NULL)

void funct(job ** pfirst, job **plast, job*newnode)
{
   if((*pfirst) == NULL)
   {
      *pfirst = *plast = newnode;
       newnode->next = NULL;
   }
   else
   {
      (*plast)->next = newnode;//<----
      *plast = (*plast)->next;//<----
   }
}

Also considering you are creating List it will be better use (Remember you can do it even without last pointer).. this approach makes it easy to create more than One list Or Array Of List

typedef struct node
{
    int pid;
    int runtime;
    struct node *next;
}job;

typedef struct List
{
    job *first = NULL;
    job *last = NULL;
}joblist;

and then something like

int main()
//code
joblist *list= NULL;
job *newnode;
//code
//from here
if( list== NULL )
{
     list =  malloc(sizeof (*list ));
     list->first =list->last=newnode;
     newnode->next = NULL;
}
else
{
     list->last->next = newnode;
     list->last = list->last->next;
}

Upvotes: 0

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58251

-> has higher precedence over *(Dereference) operator so you need parenthesis () around list to overwrite precedence. Correct it like: (*last)->next = newnode;

*last->next = newnode; is wrong because it same as *(last->next) = newnode; and list has no member next

Upvotes: 5

Related Questions