Search code examples
arrayscsegmentation-faultnested-loops

Kattis - Odd Man Out - Segmentation Fault


Please Note that this problem is for homework.

With the following code, I am inputting the data on the Kattis website for this problem. The code compiles, however, I'm getting a segmentation fault after the 'Number of Partygoers #:' printf, and I'm not sure why. Please help!

In Kattis, the description of the problem is basically: There are a number of party goers, you realize someone isn't supposed to be here because you sent all of the invitations to couples. Each party goer has a code on their invitation that matches another's. Find the odd man out.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int N,i,n,j,a,count=0,num=1;
    int guest[1000],cas[1000];
    scanf("%d",&N);
    printf("Initial N: %dn",N);

    while(N!=0)
    {
        printf("While #: %dn",N);
        scanf("%d",&n);
        printf("Number of Partygoers: %dn",n);
        for(i=0;i<n;i++)
        {
            scanf("%d",guest[i]);
            printf("Goer's Id: %dn",i);
            guest[i]=cas[i];
        }

        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                if(cas[i]==guest[j])
                {
                    printf("Is Equaln");
                    if(count==2)
                    {
                        break;
                        i++;
                        j=0;
                        printf("Count Equaln");
                    }

                    count++;
                    j++;
                }
                else
                {
                    printf("Case #%d: %dn",num,cas[i]);
                }
            }
        }
        N--;
        num++;
    }
    return 0;
}

Solution

  • scanf is expecting a pointer and you are passing a value.

    Change

    scanf("%d",guest[i]);
    

    to

    scanf("%d",&guest[i]);
    

    There is another problem, you get a value with scanf but then you overwrite this value with an uninitialized value (garbage):

    for(i=0;i<n;i++){
       scanf("%d",&guest[i]);
       printf("Goer's Id: %d\n",i);
       guest[i]=cas[i]; /* cas[i] is used uninitialized */
    }
    

    Do you mean cas[i]=guest[i];?