gpt4 book ai didi

c - c中结构指针的范围?

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:22 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<conio.h>

struct GNode{
struct gnode* nextnode;
struct gnode* arcptr;
int Visited;
}

typedef struct GNode* Grnd;

struct ArcNode{
struct arcnode* nextarc;
struct acrnode* ndptr;
}

typedef struct ArcNode* Arc;

Grnd getGraphNode(){
Grnd NewNode=(Grnd)malloc(sizeof(struct GNode));

NewNode->nextnode=NULL;
NewNode->arcptr=NULL;

return NewNode;
}

Arc getArcNode(){
Arc NewArc=(Arc)malloc(sizeof(struct ArcNode));

NewArc->nextarc=NULL;
NewArc->ndptr=NULL;

return NewArc;
}

void join(Grnd *GNode1,Grnd *GNode2){
Arc NewArc=getArcNode();
NewArc->ndptr=(*GNode2);

NewArc->nextarc=(*GNode1)->arcptr;
(*GNode1)->arcptr=NewArc;
}

Grnd addNode(Grnd *Graph){
Grnd NewNode=getGraphNode();

if((*Graph)==NULL){
(*Graph)=NewNode;
return NewNode;
}

while((*Graph)->nextnode!=NULL)
Graph=Graph->nextnode;

(*Graph)->nextnode=NewNode;

return NewNode;
}

考虑到上面的 C 代码:我担心当我调用 join 函数连接两个图节点时,它真的会连接它们吗?因为一旦程序超出 join 的范围,NewArc 就不存在了。因此,当我在创建图形后尝试找到给定节点的所有相邻节点时,我能做到吗?为什么?

最佳答案

because as soon as the program goes out of the scope of join , NewArc doesn't exist.

没错!指针本身消失了,但它指向的内存还在那里,为你分配。所以您可以自由地继续通过其他指针引用它,直到您释放它。


(*GNode1)->arcptr=NewNode;

我认为你的意思是 NewArc 而不是 NewNode

关于c - c中结构指针的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15953570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com