3

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..

4

2 回答 2

5

->比(取消引用)运算符具有更高的优先级*,因此您需要括号()list覆盖优先级。更正它像: (*last)->next = newnode;

*last->next = newnode;是错误的,因为它*(last->next) = newnode;list没有成员相同next

于 2013-05-30T16:28:23.433 回答
0

除了这里提到的解决方案之外,您的第二个代码有逻辑错误..您应该检查if(*pfirst == NULL)而不是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;//<----
   }
}

还考虑到您正在创建List它会更好地使用(请记住,即使没有last指针也可以这样做)..这种方法可以轻松创建多个列表或列表数组

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

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

然后像

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;
}
于 2013-05-30T16:37:39.117 回答