如何正确地将指针从函数返回到另一个函数?

时间:2017-07-21 17:06:42

标签: c++ pointers

我正在使用指针编写一个小程序, 这是我的代码:

    #include<iostream>

using namespace std;

struct number
{
int data;
number *next;
} test;

number * last_node(number *head)
{
    number *temp = new number;
    temp = head;

    while (temp->next != nullptr)
    {
        temp = temp->next;
    }

    return temp;

}

void insert_at_end (number *head)
{
    number *temp = new number;
    number *last = new number;
last = last_node(*head);

    cout<<"Enter the data";
    cin>>temp->data;
    temp->next = nullptr;
    last->next = temp;
}

void view_all (number *head)
{
    number *temp = new number;
    temp = head;

    while (temp->next != nullptr)
    {
        cout<<temp->data;
        temp = temp->next;
    }
}

int main()
{
    number *head = &test;
    int choice;
    char ans = 'y';

    do
    {



    cout<<"Enter your choice";
    cout<<"\n 1. Insert ";
    cout<<"\n 2. View ";
    cout<<"\n 3. Exit ";

    cin>>choice;

    switch (choice)
    {
        case 1 : insert_at_end(head);
        break;

        case 2 : view_all(head);
        break;

        case 3 : goto label;

        default : cout<<"You have entered wrong choice";
    }

    cout<<"Do you want the menu again ? (y/n)" ;
    cin>>ans;

    }

    while (ans = 'y');

    label:

        return 0;
}

编译时,如果在调用函数'last_node(* head)'时无法将“number”转换为“number *”,则会发生错误。

你能帮我理解一下吗?

1 个答案:

答案 0 :(得分:0)

您已经犯了一些错误,但直接提到了该错误,您只需要传递head指针,而不是*head指针取消引用它。有几个内存泄漏,例如你已完成的last_node()功能 -

number *temp = new number;
temp = head;

在堆上创建新的number类型并将该内存指向temp指针。现在,在下一行,您将temp更改为指向head,从而导致new number丢失。此外,在迭代您的链接列表时,您错过了最后一个元素,因此请查看我所做的修改。另一个严重错误是赋值操作,而不是== - while (ans = 'y');,请注意这些拼写错误。并且不要在goto适合的地方使用{。}}。

#include <iostream>

using namespace std;

struct number {
    int data = 0;
    number *next = nullptr;
};

number *last_node(number *head)
{
    number *temp = head;
    while (temp->next != nullptr) {
        temp = temp->next;
    }
    return temp;
}

void insert_at_end(number *head)
{
    number *temp = new number();
    number *last = last_node(head);

    cout << "Enter the data";
    cin >> temp->data;
    temp->next = nullptr;
    last->next = temp;
}

void view_all(number *head)
{
    number *temp = head;
    while (temp != nullptr) {
        cout << temp->data;
        temp = temp->next;
    }
}

int main()
{
    number *head = new number();
    int choice;
    char ans = 'y';

    do {
        cout << "Enter your choice";
        cout << "\n 1. Insert ";
        cout << "\n 2. View ";
        cout << "\n 3. Exit ";

        cin >> choice;

        switch (choice) {
            case 1: insert_at_end(head); break;
            case 2: view_all(head); break;
            case 3: return 0;
            default: cout << "You have entered wrong choice";
        }

        cout << "Do you want the menu again ? (y/n)";
        cin >> ans;
    }
    while (ans == 'y');

    return 0;
}