C将列表作为参数传递

Ale*_*ire 5 c reference list

所以我将列表定义为全局变量:

typedef struct center {

  char center_name[100];

  char hostname[100];

  int port;

  struct center *next_center;

} center;
Run Code Online (Sandbox Code Playgroud)

我需要在列表中添加元素.但是我需要添加的这些元素位于文件中,因此:

 int main(int argc, char** argv) {
     center *head = NULL; 
     parse(argv, head);
  }
Run Code Online (Sandbox Code Playgroud)

parse是一个函数,它读取文件并将这些读取的元素添加到新的中心(所有这些都可以,它会被双重检查)

void parser (char** argv, center *head) {
   //read the elements i need to add
   //creates a newCenter and adds the elements read to the new center
   //this far it works
  addToCenter(newCenter, head); 
}
Run Code Online (Sandbox Code Playgroud)

哪里:

addToCenter(center *newCenter, center *head){
   //adds newCenter to the list
   if (head == null)
      head = newCenter;
   else {
      //find last element
      lastelement.next_center = newCenter; 
   }

}
Run Code Online (Sandbox Code Playgroud)

一切正常,但Main上的列表总是返回null.换句话说,引用没有被修改.我不明白为什么,因为我传递一个指向列表的指针.

另一种解决方案我是将列表的head变量创建为全局变量,但最好避免这些情况.

提前致谢.

Who*_*aig 7

您的列表头是按值传递的.你需要通过地址传递头指针,以防它被修改(它将是).

例:

addToCenter(center *newCenter, center *head) // <=== note: passed by value
{
   //adds newCenter to the list
   if (head == null)
      head = newCenter; // <=== note: modified local stack parameter only.
   else {
      //find last element
      lastelement.next_center = newCenter; 
   }
}
Run Code Online (Sandbox Code Playgroud)

应该:

addToCenter(center *newCenter, center **head) // <=== note: now passed by address
{
   //adds newCenter to the list
   if (*head == null)
      *head = newCenter;  // <=== note: now modifies the source pointer.
   else {
      //find last element
      lastelement.next_center = newCenter; 
   }
}
Run Code Online (Sandbox Code Playgroud)

同样用解析:

void parser (char** argv, center **head) // <=== again, the head-pointer's *address*
{
   //read the elements i need to add
   //creates a newCenter and adds the elements read to the new center
   //this far it works
  addToCenter(newCenter, head);  // <=== just forward it on.
}
Run Code Online (Sandbox Code Playgroud)

最后回到主要:

int main(int argc, char** argv) 
{
     center *head = NULL; 
     parse(argv, &head);  // <=== note: passing address of the head-pointer. (thus a dbl-pointer).
}
Run Code Online (Sandbox Code Playgroud)