我有一个结构类型作为参数,需要将它传递给函数。
整个代码如下:
void insert(struct node *newt) {
struct node *node = head, *prev = NULL;
while (node != NULL && node->data < newt->data) {
prev = node;
node = node->next;
}
newt->next = node;
if (prev == NULL)
head = newt;
else
prev->next = newt;
}
void print(){
struct node *tmp = head;
while(tmp){
printf("%d->",tmp->data);
tmp = tmp->next;
}
printf("\n");
}
int main(){
/*
* Experiment for naive-insert
*/
for(int i = 1; i < 4; i++){
insert(&(struct node){.data = i, .next = NULL});
}
//insert(&(struct node){.data = 1, .next = NULL});
//insert(&(struct node){.data = 2, .next = NULL});
//insert(&(struct node){.data = 3, .next = NULL});
print();
}
如果我在 for 循环中调用 insert,它将打印 .....->3->3->3....(无法停止)
但是,如果我只是将 for 循环替换为
insert(&(struct node){.data = 1, .next = NULL});
insert(&(struct node){.data = 2, .next = NULL});
insert(&(struct node){.data = 3, .next = NULL});
它会正常运行。我想知道我的 for-loop 版本代码发生了什么。