Segmentation fault (core dumped) in Quick Union Implementaion in C

后端 未结 1 1359
时光取名叫无心
时光取名叫无心 2021-01-29 13:46
#include
#include
int *id,N;

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

    id=(in         


        
相关标签:
1条回答
  • 2021-01-29 14:34

    I would guess this is the problem

    root(int i)
    {
        int p;  
        while(p!=(*(id+p)))   <-- p uninitialised 
            p=*(id+p);
        return(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.

    0 讨论(0)
提交回复
热议问题