gpt4 book ai didi

c - C 结构体数组的寻址和分配内存

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

在从头开始编写邻接列表时,我在为结构体数组寻址和分配内存时遇到一些问题。 (忽略有向/无向列表)。
经过几个小时的调试,我发现代码仅保留(更新)邻接列表中的最后两个输入。
我想知道我实际上搞乱了内存分配和访问它的内容和方式。
请不要忘记给我有关该主题/问题的进一步研究链接。提前致谢。
这是我的代码-

/*a single node of an adjacency list*/
typedef struct adjList{

int dest;
struct adjList *next;

} adjList;


/*Image of a graph...*/

typedef struct Image{

int source;
adjList *head;

} Image;


void add_adj_edge(Image graph[], int source, int destiny);

int main() {

int vertices = 6;
Image graph[vertices];

//need not to mention detailed here
// initialize_graph(graph, vertices);

add_adj_edge(graph, 1, 2);
add_adj_edge(graph, 1, 4);
add_adj_edge(graph, 1, 5);
add_adj_edge(graph, 1, 6);
print_graph(graph, vertices);
printf("graph[1].head->dest: %d\n", graph[1].head->dest);

return 0;
}





void add_adj_edge(Image *graph, int src, int dest){

adjList *cache = malloc(sizeof(adjList));
/*create a single node*/
cache->dest = dest;
cache->next = NULL;

if(graph[src].head == NULL){
graph[src].head = cache;

}


else{

while( graph[src].head->next != NULL){
graph[src].head = graph[src].head->next;
}

graph[src].head->next = cache;

}

return;

}

输出

        node: 1    5 6 
node: 2
node: 3
node: 4
node: 5
node: 6
graph[1].head->dest: 5

Instead of

node: 1 2 4 5 6
node: 2
node: 3
node: 4
node: 5
node: 6
graph[1].head->dest: 2

最佳答案

正如我在评论中提到的,您的源代码存在一些缺失,并且对如何更新链接列表也存在误解。

第一个问题:(在 main() 中分配 Image graph[vertices]; 不会初始化值)。

It is necessary to set adjList *head; property to NULL to be sure that if(graph[src].head == NULL) will be true at the first access.

int vertices = 6;
Image graph[vertices];
for(int i=0;i<vertices;i++) {
graph[i].head = NULL; // list is empty
graph[i].source = 0; // or what ever you want
}

第二个问题:(在链表末尾添加新节点时,需要使用临时变量来探索前一个节点)。

If you are using graph[src].head = graph[src].head->next; you will overwrite all previous nodes by the last one.

add_adj_edge()中使用以下方法来探索节点:

        adjList *pTmp;

// point to the first node
pTmp = graph[src].head;
// explore node until the last has no node
while( pTmp->next != NULL){
pTmp = pTmp->next;
}
// update the next node
pTmp->next = cache;

关于c - C 结构体数组的寻址和分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702855/

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