c - 链表使用中的段错误C

标签 c linked-list segmentation-fault declaration

我编写了一个返回段错误错误的代码。代码很长,但我将其主要部分写如下。请注意,主函数内已定义函数的所有变量均已定义,并且我测试了代码,它没有进入 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等于 04但在那之后就不会了,并且没有任何东西可以阻止它变得更大。

考虑更改您的 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/

相关文章:

c - 在c中将字符串插入链表时出现垃圾字符

python - 段错误捕获

c - 将数千个数据结构保存在一个文件中并进行特定查找是否实用?

c - 我如何让 C 识别未正确安装的库?

c - 无法使用 fgets 函数读取字符串

java - 这段代码有什么问题(简单链表)

c - 将节点插入已排序的双向链表

android - C++ 段错误输出

c - 当我接受矩阵的第一个值时出现段错误

c# - C# 和 C 之间的串行连接通信时遇到问题