链接列表分段故障
typedef struct node{
int data;
struct node *link;
}nd;
nd *head=NULL , *ahead=NULL;
void create_node(int item) {
nd *new, *temp;
new = (nd*)malloc(sizeof(nd));
new->data=item;
new->link=NULL;
if(head==NULL) {
head=new;
}
else {
temp=head;
while(temp->link!=NULL) {
temp=temp->link;
}
temp->link=new;
}
}
void alpha_check(int size) {
int i,j,num;
nd *ti , *tj;
ti=tj=head;
for(i=1 ; i<=size ; i++) {
for(j=1 ; j<=size ; j++) {
num = ((ti->data)*10)+(tj->data);
tj=tj->link;
/*if(num>=65 && num<=90) {
printf("\n->%d",num);
}*/
}
//ti=ti->link;
}
}
void traverse(nd *thead) {
while(thead->link!=NULL) {
printf("%d ",thead->data);
thead=thead->link;
}
printf("%d ",thead->data);
}
所以在上面的代码唯一的问题在于功能alpha_check我想要的变量TJ点到下一个节点()。而不是指向下一个节点,它给了我分段错误(核心转储)。 请解释为什么我不能让tj指向下一个节点。链接列表分段故障
分段错误是内核发出的一个信号,表示程序正在访问内存,它没有权限导致内核终止程序。这通常意味着你超出了数组的界限,或者在你的情况下,你正在引用一个指向它不应该是的东西的指针。像其他人暗示的其他人一样,遍历链表时需要使用不同类型的约束,而不是遍历数组时的约束。在检查节点指针不是NULL而不是在for循环中做一些固定大小的时候,你需要遍历它。
我对您的alpha_check过程进行了更改,并添加了一个用于测试它的主体。它可以像你期望的那样工作。
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* link;
} nd;
nd *head=NULL , *ahead=NULL;
void create_node(int item) {
nd* new,* temp;
new = (nd*)malloc(sizeof(nd));
new->data = item;
new->link = NULL;
printf("%d %p\n", new->data, new);
if(head == NULL) {
head = new;
}
else {
temp = head;
while(temp->link)
temp = temp->link;
temp->link = new;
}
}
void alpha_check(int size) {
int i,j,num;
nd* ti ,* tj;
ti = tj = head;
for(i = 1 ; i <= size ; i++) {
while(tj) {
num = ti->data * 10 + tj->data;
tj = tj->link;
//if(num>=65 && num<=90)
//{
printf("\n->%d",num);
printf(" %p\n", tj);
//}
}
//ti=ti->link;
}
}
void traverse(nd* thead) {
while(thead->link) {
printf("%d ", thead->data);
thead = thead->link;
}
printf("%d ", thead->data);
}
int main(void) {
create_node(10);
create_node(1);
create_node(5);
alpha_check(2);
return 0;
}
如果您创建一个包含头指针和一些跟踪列表大小的变量的结构,则可以使用for循环的大小。 'struct List { size_t size; nd * head; nd * head; }' 您也可以使用for循环代替while循环来检查指针是否为空'for(tj = head; tj; tj = tj-> link)' –
感谢您的帮助。有用。 –
为(I = 1; I link!= NULL –
我们看不到如何创建列表,也不知道如何调用'alpha_check'。看起来这个“大小”是错误的。使用大小而不是while循环遍历列表直到列表结束也很奇怪。使用调试器。它会告诉你什么是错的,它发生在哪里。 –
你传递给函数alpha_check的大小是多少? – Ganeshdip