【发布时间】:2015-07-01 08:43:32
【问题描述】:
为什么这段代码给出了正确的答案?
我正在返回一个指针。但是返回这个没有分段错误。这段代码的完整机制是什么?
谁能告诉input() 函数是如何工作的以及它如何返回链表的头部?
#include<bits/stdc++.h>
using namespace std;
typedef struct a{
int data;
struct a* next;
}link;
typedef link *node;
//Function to take input of linked list//
node input()
{
int n,i;
cout<<"Enter the size of the linked list\t";
cin>>n;
node g,header,rear;
cout<<"Enter the elements\n";
g=new link;
g->next=NULL;
cin>>g->data;
header=g;
rear=g;
for(i=1;i<n;i++)
{
g=new link;
cin>>g->data;
g->next=NULL;
rear->next=g;
rear=g;
}
return header;
}
void output(node f)
{
cout<<"Linked List ELEMENTS\n";
//cout<<"\nThe content of linked list is\n";
while(f!=NULL)
{
cout<<f->data<<"\t";
f=f->next;
}
}
int main()
{
node head,f;
head=input();
output(head);
return 0;
}
【问题讨论】:
-
这个程序是你自己写的吗?
-
为什么会出现分段错误?仅当您要返回指向局部变量的指针时,从函数返回指针才是问题。
header是指向链表头的指针,它是使用new动态分配的。
标签: c++ pointers linked-list