gpt4 book ai didi

c - 我在图中添加顶点的 C 实现失败

转载 作者:行者123 更新时间:2023-11-30 14:49:37 25 4
gpt4 key购买 nike

这是我的玩具程序,用于将顶点添加到图中:

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
typedef struct EdgeNode{
int adjvex;
struct EdgeNode *nextarc;
}ENode, *PENode;
typedef struct VertexNode{
char *data;
ENode *firstarc;
}VNode;

typedef struct MyGraph{
VNode vertices[INT_MAX];

}Graph;



/**void make_node(Graph *G, char *first){
int i = 0;
G.vertices[i++].data = first;
G.vertices[i].firstarc = NULL;
while(i--){
printf("the node is %s\n",G.vertices[i].data);
}
}**/

int main (){
size_t sz1;
char *line = NULL;
//char line[1024];
char make_nodes[] = "@n";
char make_edges[] = "@e";
char check_edges[] = "@q";
static int i = 0;
int is_make_node = 0;
//Graph* pGraph;
Graph* pGraph = malloc(sizeof(Graph));
if (pGraph == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(1);
}


while(getline(&line, &sz1, stdin) > 0){
char cmd[3],n1[65],n2[65],dummy[2];
int num_args;
num_args = sscanf(line,"%3s%64s%64s%2s",cmd,n1,n2,dummy);
if (strcmp(cmd,make_nodes) == 0){
if(num_args != 2){
printf("error\n");
}else{
pGraph->vertices[i].data = n1;
pGraph->vertices[i].firstarc = NULL;
printf("the node is %s\n",pGraph->vertices[0].data);
i++;
}
}
}
printf("---");
printf("the node is %s\n",pGraph->vertices[0].data);
printf("the node is %s\n",pGraph->vertices[1].data);
printf("the node is %s\n",pGraph->vertices[2].data);
return 0;
}

现在奇怪的事情发生了,我想一一添加顶点,当我运行代码时,它给出了这样的结果:

@n hey
the node is hey
@n jude
the node is jude
---
the node is jude
the node is jude
the node is (null)

@n(某物)意味着添加一个名为某物的节点,而我的预期输出应该是:

@n hey
the node is hey
@n jude
the node is jude
---
the node is hey
the node is jude
the node is (null)

有人发现问题了吗?我不知道为什么当我读取一个新顶点时,前一个顶点被新顶点“覆盖”。

最佳答案

使用pGraph->vertices[i].data = n1;,您可以让.data指向具有 block 作用域的(局部)变量,该变量的生命周期将结束一旦超出范围。因此,当您随后访问 vertices[x].data 时(即在循环之后,实际上甚至在循环中的第二次运行时,这会使第一次运行的局部变量无效),您会得到未定义的行为。

要解决这个问题,请分配内容的副本:

pGraph->vertices[i].data = malloc(strlen(n1)+1);
strcpy(pGraph->vertices[i].data, n1);

或者简而言之(如果您的平台上可用):

pGraph->vertices[i].data = strdup(n1);

关于c - 我在图中添加顶点的 C 实现失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435981/

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