gpt4 book ai didi

c - Mingw 使用 malloc 作为结构体

转载 作者:行者123 更新时间:2023-11-30 20:23:19 25 4
gpt4 key购买 nike

我刚刚在作业中遇到了 malloc 问题//这是我的头文件

struct vertex_t {
int id;
char *label;

/* A list of vertices representing incoming edges */
List in;
/* A List of vertices representing outgoing edges */
List out;
};
struct graph_t {
/* Number of vertices */
int order;
/* Numb er of edges */
int size;
Vertex vertices;
};

//我们不允许改变上面的头文件。在我的主文件中,如何 malloc 图中的顶点?

Graph new_graph(int order) {
Graph graph;
int i;
graph=NULL;
graph=(Graph)malloc(sizeof(Graph));
assert(graph);
graph->order=order;
graph->size=0;
graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));//!!!!!!!!!!!!!!!!!!!this line!!!!
for(i=0;i<order;i++){
graph->vertices[i].label=(char*)malloc(MAX_LINE_LEN*sizeof(char));
graph->vertices[i].in=NULL;
graph->vertices[i].out=NULL;
}
return graph;
}

我只能在malloc中添加极大的数字来防止内存泄漏。

最佳答案

很难看到所有错误,因为您没有提供完整的程序,但据我所知,您在以下几行中犯了错误:

graph=(Graph)malloc(sizeof(Graph));
graph->vertices=(Vertex*)malloc((order+100000)*sizeof(Vertex));

GraphVertex似乎是指针类型,所以你应该这样做:

graph = malloc(sizeof(struct graph_t));
graph->vertices = malloc((order)*sizeof(struct vertex_t));

我假设Vertex是与 struct vertex_t 关联的指针类型和Graph是与 struct graph_t 关联的指针类型在你的标题中。

我们不使用malloc()为指针本身分配内存,但为其指向的数据分配内存。所以大小取决于数据。如果pType是指针类型,例如 char * , int *struct my_struct * , sizeof(pType)将始终相同(例如,32 位程序为 8,64 位程序为 16)。

关于c - Mingw 使用 malloc 作为结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36348343/

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