【发布时间】:2019-08-02 12:53:07
【问题描述】:
我正在用 C 语言创建一个简单的结构数组,但第一个结构总是乱码。我该如何解决这个问题?
我尝试过以多种方式将双指针的第一个元素设置为 struct,但总是失败。
这是我的 graph.h 文件:
#ifndef GRAPH_H
#define GRAPH_H
#include "set.h"
typedef struct urlNode * URLList;
typedef struct GraphRep * Graph;
struct urlNode {
int id;
char* URL_NAME;
URLList next; // link to next node
};
struct GraphRep {
int nV;
URLList * collections;
};
Graph newGraph(Set s);
int nameToId(Graph g, char *name);
void showGraph(Graph g);
#endif
而我的 newGraph(Set s) 函数如下所示:
Graph newGraph(Set s){
int size = nElems(s);
Graph new_graph = malloc(sizeof(struct GraphRep));
if (new_graph == NULL) {
printf("ERROR: COULDNT ALLOCATE GRAPH\n");
}
new_graph->nV = size;
char *name = getNextVal(s);
// THIS IS THE NODE TO BE ADDED TO THE GRAPH
URLList list_to_add = malloc(sizeof(struct urlNode));
list_to_add->URL_NAME = strdup(name);
list_to_add->id = 0;
list_to_add->next = NULL;
// HERE I ADD THE NODE TO THE GRAPH.
new_graph->collections[0] = list_to_add;
// PRINT OUT THE VALUES OF THE NEWLY ADDED NODE TO MAKE SURE IT WORKS
// THE URL_NAME IS PRINTED OUT FINE
// BUT THE ID IS JIBBERISH.
printf("%s\n", new_graph->collections[0]->URL_NAME);
printf("%d\n", new_graph->collections[0]->id);
if(new_graph->collections[0]->next != NULL) {
printf("%s\n", new_graph->collections[0]->next->URL_NAME);
printf("%d\n", new_graph->collections[0]->next->id);
}
printf("\n");
return new_graph;
}
我希望 new_graph->collections[0]->id 为 0,但它不断给我随机整数。 此外,即使新声明的指向 struct 的指针的下一个是 NULL,它仍然给我一个乱七八糟的下一个值。 任何帮助将不胜感激,谢谢!
【问题讨论】:
-
@Emalp 指针集合未初始化。
-
您正在将 new_graph->collection[0]->id 设置为一个指针 (list_to_add),这可能不是您想要的。我不清楚你想做什么。也许您想将其设置为 list_to_add->id?
标签: c pointers memory-management struct