分割故障(核心转储)的快速联盟Implementaion C语言 [英] Segmentation fault (core dumped) in Quick Union Implementaion in C

查看:262
本文介绍了分割故障(核心转储)的快速联盟Implementaion C语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<stdlib.h>
int *id,N;

main()
{
    FILE* file=fopen("a.txt","r");
    int i,p,q,c;
    fscanf(file,"%d",&N);

    id=(int *)malloc(N*sizeof(int));

    for(i=0;i<N;i++)
        *(id+i)=i;

    while(!feof(file))
    {
        fscanf(file,"%d %d",&p,&q);
        if(!connected(p,q))
            unn(p,q);
    }
    fclose(file);
    c=1;

    while(c==1)
    {
        scanf("%d %d",&p,&q);
        printf("%d\nYes(1) or No(0)    ",connected(p,q));
        scanf("%d",&c);
    }
}

connected(int p,int q)
{
    return((root(p))==(root(q)));
}

unn(int p,int q)
{
    int j=root(q);
    int i=root(p);
    *(id+j)=i;
}

root(int i)
{
    while(i!=(*(id+i)))
        i=*(id+i);
    return(i);
}

在编译时,不显示错误消息。但是,当我尝试执行这个程序,它说:分段错误(核心转储)。为什么会出现这种情况? 由于可能已经注意到,这是实施快速联合的尝试。

On compiling, no error message is displayed. However, when I try to execute this program, it says"Segmentation Fault (core dumped). Why does this happen? As may have noticed, this is an attempt to implement the quick union.

快速查找未经使用相同的文件a.txt中只用了一些调整,以这种code任何麻烦来实现。 *的是或否是用于用户的查询。

The quick find was implemented without any hassle using the same file "a.txt" with only a few tweaks to this code. * The Yes or No is for the user's query.

推荐答案

我猜这就是问题所在。

root(int i)
{
    int p;  
    while(p!=(*(id+p)))   <-- p uninitialised 
        p=*(id+p);
    return(p);
}

由于 P 是未初始化的,但你正在使用它作为一个指针引用的偏移量。即使这不是原因,它仍然是一个大问题。

because p is uninitialised but you are using it as an offset in a pointer dereference. Even if it is not THE reason it is still a big problem.

您已经从编辑的问题离开

You have since edited the question to leave

root(int i)
{
    int i;  
    while(i!=(*(id+i)))  
        i=*(id+i);
    return(i);
}

在您重新定义了变量本地以及传递函数参数变量。

in which you redeclare an i variable locally as well as a i variable passed as function parameter.

这篇关于分割故障(核心转储)的快速联盟Implementaion C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆