【问题标题】:why isn't a function executing after a specific function为什么在特定功能之后没有执行功能
【发布时间】: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() 函数之前起作用?
  • 这是未定义的行为。它可能有效,也可能无效,它可能有效,然后无效。它可能不起作用,然后起作用。您违反了代码合同,因此任何结果都是“正确的”。

标签: c++ function methods


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-17
    • 2010-12-07
    • 2017-10-13
    • 2018-06-23
    • 1970-01-01
    • 2013-09-08
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多