链表结构(将结构指针传递给函数)
Linklist Structure (passing strucure pointer to a function )
我为链表做了一个结构,然后全局声明了它的指针,然后做了两个函数来添加节点和显示列表。当我在全局范围内声明结构指针时,一切都很好
但后来我在主函数中声明了指针,并根据需要更改了代码。但现在当我编译并运行exe时。它让我xxxx.exe停止工作!
Tldr:向函数传递了结构指针,但它不起作用!
#include<iostream>
using namespace std;
struct node {
int data;
node *adr;
};
void insertate(int n, struct node *h)
{
struct node *temp;
temp = new node;
temp->data=n;
temp->adr=NULL;
if(h==NULL)
{
h=temp;
}
else
{
struct node *q;
q= new node;
q=h;
while(q->adr!=NULL)
{
q=q->adr;
}
q->adr=temp;
}
}
void print(struct node *h)
{
struct node *c=h;
while(c!=NULL)
{
cout<<c->data;
c=c->adr;
cout<<endl;
}
}
int main()
{
struct node *a;
insertate(5,a);
insertate(4,a);
insertate(31,a);
insertate(32,a);
insertate(34,a);
insertate(36,a);
print(a);
return 0;
}
在main()中首先分配头部节点
struct node *a = new node;
然后尝试通过参考:
insertate(5, &a);
您还需要更新您的方法定义,而不是*h,它将是**h,如下所示:
#include <iostream>
using namespace std;
struct node {
int data;
node *adr;
};
void insertate(int n, struct node **h) {
struct node *temp;
temp = new node;
temp->data=n;
temp->adr=NULL;
if(h==NULL) {
*h=temp;
}
else
{
struct node *q;
q= new node;
q=*h;
while(q->adr!=NULL)
{
q=q->adr;
}
q->adr=temp;
}
}
void print(struct node **h)
{
struct node *c=*h;
while(c!=NULL)
{
cout<<c->data;
c=c->adr;
cout<<endl;
}
}
int main() {
struct node *a = new node;
a->data = 0; // Set this to initial head value
a->adr = NULL;
insertate(5, &a);
insertate(4, &a);
insertate(31, &a);
insertate(32, &a);
insertate(34, &a);
insertate(36, &a);
print(&a);
return 0;
}
此外,当您访问方法内部的h时,由于它是指向指针的指针,您将需要取消引用,因此请注意:
q = *h;
您可以点击下面的链接进行测试,您可能需要更新您的打印功能,以便不打印出当前为0的头值:
在线试用!
通过这种方式,我们通过在主函数中使用新的运算符来分配堆上的头指针。有些人给头指针一个伪变量,但在这种情况下,我认为在主函数中初始化更容易。现在我们有了一个指向堆中内存的指针,我们可以使用它的地址(aka&operator)将其传递给我们的函数。这将创建一个指向其类型的指针(**h)的指针。就像使用常规指针一样,我们需要取消引用它才能访问它的值,这就是为什么我们在访问头指针时使用*h的原因。
相关文章:
- 使用不带参数的函数访问结构元素
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 链表,反向函数,数据结构
- 结构向量中自定义结构函数的内存使用
- C++ 中的嵌套结构函数
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 如何将值从外部传递到结构函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- C++结构函数的多个定义
- C++ 另一个标头中的结构函数给出"missing type specifier"
- 如何在C中找到结构/函数的父头文件
- C++二进制文件到结构函数
- C++ 将结构函数作为继承结构中函数的参数传递
- 如何在 main 之外的类中使用结构函数
- 在类中使用结构函数,在基类 c++ 中使用变量
- C++ 结构函数体调用另一个结构函数,同一个模块
- 是存储在对象中的类/结构函数
- Eclipse CDT 在从 std::map 访问时无法解析结构函数
- C++模板自身名称作为模板模板参数在同一模板结构函数内传递
- 如何使用真正的字符串类型来表示类结构函数中的字符串