【发布时间】:2019-07-12 13:51:34
【问题描述】:
在我的代码中,temp1print() 函数在 print() 函数之前执行,但在 print() 函数之后不执行。
下面的程序是在链表的末尾插入数据。 我想知道为什么将 temp1Print() 函数放在 print() 函数之后没有执行。
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
struct Node* head;
struct Node* temp1;
struct Node* Insert(struct Node* head,int data){
temp1 = head;
Node* temp = new Node;
temp->data = data;
temp->next = NULL;
if(head == NULL){
head = temp;
printf("head after inserting %d is %d\n",temp->data,head);
printf("temp1 after inserting %d is %d\n",temp->data,temp1);
return head;
}
else{
while(temp1->next!=NULL){
temp1 = temp1->next;
}
temp1->next = temp;
printf("temp1 after inserting %d is %d\n",temp->data,temp1);
printf("temp1->data=%d temp1->next=%d\n\n",temp1->data,temp1->next);
return head;
}
}
void print(Node* head){
Node* temp = head;
printf("head = %d\n",head);
while(temp!=NULL){
printf("%d ",temp->data);
temp = temp->next;
}
printf("%d",temp->data);
}
void temp1Print(){
printf("temp1 = %d\n",temp1);
}
int main(){
head = NULL;
head = Insert(head,2);
head = Insert(head,4);
head = Insert(head,6);
head = Insert(head,8);
temp1Print(); //This function is working when placed before the print function
print(head);
temp1Print(); //Why isn't this function working when placed after the print function?
}
【问题讨论】:
-
printf("temp1 = %d\n",temp1)是未定义的行为。temp1不是int。 -
@NathanOliver 那么为什么它在 print() 函数之前起作用?
-
这是未定义的行为。它可能有效,也可能无效,它可能有效,然后无效。它可能不起作用,然后起作用。您违反了代码合同,因此任何结果都是“正确的”。