C 为什么这个代码不能被执行?
我正在使用链表进行图形插入。下面的代码正常工作C 为什么这个代码不能被执行?,c,pointers,graph,linked-list,adjacency-list,C,Pointers,Graph,Linked List,Adjacency List,我正在使用链表进行图形插入。下面的代码正常工作 #include <stdio.h> #include <stdlib.h> #define new_node (struct node*)malloc(sizeof(struct node)) struct node { int index; struct node* next; }; void addEdge(struct node* head, int parent, int child) {
#include <stdio.h>
#include <stdlib.h>
#define new_node (struct node*)malloc(sizeof(struct node))
struct node {
int index;
struct node* next;
};
void addEdge(struct node* head, int parent, int child) {
struct node* temp = new_node;
temp->index = child;
temp->next = (head+parent)->next;
(head+parent)->next = temp;
struct node* tmp = new_node;
tmp->index = parent;
tmp->next = (head+child)->next;
(head+child)->next = tmp;
return;
}
struct node* create_graph( int v ) {
struct node* temp = ( struct node* )malloc( v*sizeof(struct node) );
for( int i = 0; i < v; i++ ) {
(temp+i)->index = i;
(temp+i)->next = NULL;
}
return temp;
}
void printGraph(struct node* head, int vertex) {
struct node* temp;
for( int i = 0; i < vertex; i++ ) {
printf("All nodes connected to node %d is ", (head+i)->index);
temp = (head + i)->next;
while(temp != NULL) {
printf("-> %d", temp->index);
temp = temp->next;
}
printf("\n");
}
}
int main(void) {
int v; // Number of vertex in graph.
struct node* head = NULL;
v = 5;
//scanf( "%d", &v );
head = create_graph( v );
addEdge(head, 0, 1);
addEdge(head, 0, 4);
addEdge(head, 1, 2);
addEdge(head, 1, 3);
addEdge(head, 1, 4);
addEdge(head, 2, 3);
addEdge(head, 3, 4);
printGraph(head, 5);
return 0;
}
下面这句话是我无法思考的主要问题:
为什么这一行会导致代码出现运行时错误
temp = (temp+i)->next;
p.S.编译器使用的是GCC 6.3。错误在内部while循环中,您已到达temp==NULL以退出while循环,并且在外部for循环的第一行调用temp+i->index。由于temp为null,您将得到错误 但是,在第一个代码中,您在外循环的开头使用head而不是temp,而第二个代码使用temp。因此,您可以更改头部的temp base值,与第二种情况相比,temp的null值没有任何问题
要解决此问题,您可以启动另一个变量,如temp as new_temp,在内部while循环中使用,并区分内部循环和外部循环的逻辑。请包含准确的错误消息;temp+i可能不是有效的内存地址。@PhilippLudwig SIGSEGV是错误消息。您试图同时将temp用于两个目的:用于在头数组上迭代,以及用于在链接列表中迭代。你不能用一个变量同时做这两件事,你需要两个变量。@Sanderedycker我理解我所犯的错误,感谢你的评论。首先,感谢你花时间回答我的问题,你能解释一下这与上述正确代码的区别吗?非常感谢。现在我能够理解为什么我会犯这个错误,实际上这是一个愚蠢的错误。
temp = (temp+i)->next;