【发布时间】:2013-01-26 13:52:30
【问题描述】:
所以我将列表定义为全局变量:
typedef struct center {
char center_name[100];
char hostname[100];
int port;
struct center *next_center;
} center;
我需要向列表中添加元素。但是我需要添加的这些元素都在一个文件中,所以:
int main(int argc, char** argv) {
center *head = NULL;
parse(argv, head);
}
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);
}
地点:
addToCenter(center *newCenter, center *head){
//adds newCenter to the list
if (head == null)
head = newCenter;
else {
//find last element
lastelement.next_center = newCenter;
}
}
一切正常,除了 Main 上的列表总是返回为 null。换句话说,引用没有被修改。我不明白为什么,因为我正在传递一个指向列表的指针。
虽然我的另一个解决方案是将列表的头变量创建为全局变量,但最好避免这些情况。
提前致谢。
【问题讨论】:
-
你已经修改了传入的指针值'head',它在堆栈上。