Hey I am getting segmentation fault can anyone help me out with the code

0 votes
asked Oct 23, 2019 by Sanjana (120 points)

#include<stdio.h>

#include<stdlib.h>

#include<math.h>

void printtable(int a[][4])

{

printf("          Candidate  Candidate  Candidate  Candidate\nPrecinct\tA\tB\tC\tD \n");

int i,j;

for(i=0;i<5;i++)

{

printf("%d\t\t",i+1);

for(j=0;j<4;j++)

{

printf("%d\t",a[i][j]);

}

printf("\n");

}

}

void totalvotes(int b[],double s)

{

printf("\nThe total no of votes received by each candidate and the percentage of the total votes cast:\n");

int i;

double x;

printf("\t\tA\tB\tC\tD \n");

printf("total votes     ");

for(i=0;i<4;i++)

{

printf("%ld    ",b[i]);

}

printf("\npercentage     ");

for(i=0;i<4;i++)

{

x = b[i];

x= (x/s)*100;

printf("%.2lf   ",x);

}

}

void winner(int b[],double s)

{

int i;

double x,c[4];

int f=0;

for(i=0;i<4;i++)

{

x = b[i];

c[i]= (x/s)*100;

if(c[i]>50)

{

f = i+1;

break;

}

}

printf("\n\n");

if(f>0)

{

switch(f)

{

case 1: printf("A is the winner"); break;

case 2: printf("B is the winner"); break;

case 3: printf("C is the winner"); break;

case 4: printf("D is the winner"); break;

}

}

else

{

int n=0,m=0,ni,mi;

for(i=0;i<4;i++)

{

if(c[i]>n)

{

m=n;

mi = ni;

n=c[i];

ni=i;

}

}

printf("Their is a runoff b/w %c and %c",'A'+ni,'A'+mi);

}

}

int main()

{

FILE *f = fopen("input2.txt","r");

int a[5][4],i,j;

for(i=0;i<5;i++)

{

for(j=0;j<4;j++)

{

fscanf(f,"%d",&a[i][j]);

}

}

printtable(a);

int b[4]={0};

double s=0;

for(i=0;i<4;i++)

{

for(j=0;j<5;j++)

{

b[i] = b[i] +a[j][i];

s+=a[j][i];

}

}

totalvotes(b,s);

winner(b,s);

fclose(f);

}

Inputs are

192 48 206 37
147 90 312 21
186 12 121 38
114 21 408 39
267 13 382 29

1 Answer

0 votes
answered Oct 25, 2019 by gameforcer (2,950 points)
edited Oct 25, 2019 by gameforcer

Your code seems fine to me, although it gets segmentation fault when the file input2.txt doesn't exist. Good practice in C is to have some sort of guard against the failure of fopen(), for example simply:

FILE *f = fopen("input2.txt","r");

if (f)
{
    //your code
}

optionally:

FILE *f = fopen("input2.txt","r");

if (f)
{
    //your code
}
else
{
    //error indicating that file wasn't opened
}

Also a minor detail to this line:

printf("%ld    ",b[i]);

%ld is used to display long int, while b[i] is an integer and therefore %d should be used, as follows:

printf("%d    ",b[i]); 

@edit I forgot to mention that your problem migh lay in naming your file on onlinegdb. You might have made file named "input2" while your program is looking for "input2.txt".

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...