将结构指针声明为函数的返回类型

Declaring a structure pointer as a return type for a function

本文关键字:函数 返回类型 声明 结构 指针      更新时间:2023-10-16

以下代码给出了错误 - "声明语法错误" 这里的节点是一个结构(对于链接列表)[如果我是编程的新手,请原谅我,如果我是一个愚蠢的问题]

node * enter(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}

完整代码 -

#include <iostream.h>
#include <conio.h>
void main()
{
    clrscr();
    struct node {
        int info;
        node* next;
    } * ptr, *y, *save, *start;
    void insert(node*);
    node* enter(int);
    void display(node*);
    start = NULL;
    int inf;
    cout << "Enter INFO:";
    cin >> inf;
    y = enter(inf);
    insert(y);
    cout << "display:n";
    display(start);
    getch();
}
node* enter(int n)
{
    ptr = new node;
    ptr->info = n;
    ptr->next = NULL;
    return ptr;
}
void insert(int* m)
{
    if (start == NULL) {
        start = m;
    }
    else {
        save = start;
        start = m;
        m->next = save;
    }
}
void display(node* l)
{
    while (l != NULL) {
        cout << l->info << "->";
        l = l->next;
    }
    cout << "nOVER";
}

您的主要问题是您在main内声明节点和ptr。您对Enter和其余功能的功能定义将不会看到Main()内的声明。您需要移动

struct node {
    int info;
    node* next;
} * ptr, *y, *save, *start;

到int main()修复此问题。