我编写了一个返回段错误错误的代码。代码很长,但我将其主要部分写如下。请注意,主函数内已定义函数的所有变量均已定义,并且我测试了代码,它没有进入 Function_1 内部。这就是为什么我认为问题出在声明之类的事情
typedef struct node_type
{
int data;
struct node_type *next;
} node;
typedef node *list;
void Function_1(list R, int *Matrix, int Length, int A);
int main()
{
int S = 5;
int A = 1;
int Mat1[5];
//int *Mat = malloc(S*sizeof(int));
int *Mat = &Mat1[0];
printf("Enter the Matrix with length of 10:\n");
for (int i = 0; i < S; i++)
{
scanf("%i", &(*(Mat+i)));
}
list head;
head = (list)malloc(sizeof(node));
head->next = NULL;
for (int i = 0; i < S; i++)
{
printf("%d\t", *(Mat+i));
}
//printf("\nEnter the Array = \n");
//scanf("\n%d", &A);
printf("\nA = %i", A);
Function_1(head, Mat, S, A);
while (head != NULL)
{
printf("%d\t", head->data);
head = head->next;
}
return 0;
}
void Function_1(list R, int *Matrix, int Length, int A)
{
printf("11111");
list tail;
tail = R;
int Counter = 0;
int i = 0;
while (tail != NULL)
{
if (*(Matrix+i) == A)
{
Counter++;
tail->next = (list)malloc(sizeof(node));
tail->next->data = i;
tail->next->next = NULL;
tail = tail->next;
}
i++;
}
R->data = Counter;
printf("%d", Counter);
}
谢谢
最佳答案
根据您提供的代码,我可以说由于缺少<stdlib.h>
而发生段错误或访问冲突。或<malloc.h>
包含,导致malloc
假设,然后 head
被指派做与你预期不同的事情。
我不知道,这也可能是由于代码中的随机点而发生的...
编辑:
根据您的最新编辑,在函数内的循环内 Function_1
,您正在尝试访问内存位置 Matrix + i
的内容,与 i
没有界限。可以访问i
等于 0
至4
但在那之后就不会了,并且没有任何东西可以阻止它变得更大。
考虑更改您的 while
条件进入i < 5
或类似的东西。我不知道你的目标是什么 while ( R != NULL )
但是R
在整个循环中永远不会改变,因此条件一旦为真后就不会变为假,反之亦然。
编辑2:
类似于 while
条件相当tail != NULL
其计算结果为 0
仅当 malloc
分配内存失败。 i
很可能会超过4
在你用完这么多内存之前 malloc
开始失败。
关于c - 链表使用中的段错误C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273416/