为什么没有在特定功能之后执行功能

时间:2019-07-12 13:51:34

标签: c++ function methods

在我的代码中,将temp1print()函数放置在print()函数之前执行,但是不执行,将其放置在print()函数之后。

以下程序将在链接列表的末尾插入数据。 我想知道为什么将print1)放在temp1Print()函数后不执行。

代码:

#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?
}

1 个答案:

答案 0 :(得分:3)

print函数中,当printf("%d",temp->data);指针为temp时,最后一个NULL被调用。这意味着您要取消引用无效的指针,从而导致未定义的行为。