于是,我试着做这样的事情:C /指针 - 声明一个局部变量的指针没有初始化它
void place(struct node * list, int elem){
struct node *tmp = list;
struct node *prev ;
while(tmp && tmp->info <= elem){
prev = tmp;
tmp = tmp->next;
}
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = elem;
new->next = prev->next;
prev->next = new;
}
它给了我一个分段错误。 gdb没有帮助 - 显示回溯满000000和??。
但是,当我尝试这样做:
void place(struct node * list, int elem){
struct node *tmp = list;
struct node *prev = tmp;
while(tmp && tmp->info <= elem){
prev = tmp;
tmp = tmp->next;
}
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = elem;
new->next = prev->next;
prev->next = new;
}
它工作得很好!两者之间的唯一区别是我在第二种情况下初始化局部变量指针prev,而在第一种情况下我没有这样做。但我不明白为什么第一种情况应该是分段错误?
有人能解释一下吗?
谢谢!
不错 - 我使用gcc 4.4.3 - 也许我必须启用C99语法检查才能符合你所说的内容,现在看起来有点松懈:) – Anonymous 2011-01-24 15:38:24