0

when i am running the below code to find max literacy rate and max income, the program is taking inputs properly but finally when displaying output for last two printf statements, i am getting the following error "segmentation fault.core dumped." Please explain what is wrong..Thanks in advance.

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

#define MAX 50
struct state_det {
char name[50];
long population;
float literacy;
long income;
}s[MAX];

int main()
{
int n,i,max_lit = 0, max_income = 0;
int t, p;
printf("enter number of states\n");
scanf("%d",&n);

for(i = 0; i < n; i++)
{
printf("enter the name of the state %d\n",i);
scanf("%s",&s[i].name);
printf("enter the population of the state %d\n",i);
scanf("%ld",&s[i].population);
printf("enter the literacy rate of the state %d\n",i);
scanf("%f",&s[i].literacy);
printf("enter the average income of the state %d\n",i);
scanf("%ld",&s[i].income);
}

max_lit = s[0].literacy;
max_income = s[0].income;

for(i = 1; i < n; i++)
{
if(max_lit < s[i].literacy)  {
max_lit = s[i].literacy;
t = i;
}

if(max_income < s[i].income) {
max_income = s[i].income;
p = i;
}
}

printf("\nthe state with highest literacy is %s and rate = %f\n",s[t].name, s[t].literacy);

printf("\nthe state with highest income is %s and rate = %ld\n",s[p].name, s[p].income);


return 0;
}
user2923786
  • 11
  • 1
  • 3

3 Answers3

0

The line

scanf("%s",&st[i].name);

should be

scanf("%s",s[i].name);

because specifier %s is looking for char* and you are trying to pass char (*)[50].

Dayal rai
  • 6,115
  • 19
  • 28
0

dont use scanf for strings instead use fgets(s[i].name,50,stdin)

since scanf cannot read spaces in a string. Say you enter hello world though the size is less than 50 it only takes hello into consideration and world is not stored in the string because as soon as space character is detected the string reading is terminated by scanf

and also t and p values must be initialized to 0 if the zeroth element is itself the maximum literacy and income. The value of t and p are garbage values

Read them to understand why not to use & for reading strings in scanf

C: why no & for strings in scanf() function?

scanf() does not read input string when first string of earlier defined array of strings in null

why we do not use '&' in scanf for char arrray

Reading a string with scanf

Community
  • 1
  • 1
niko
  • 8,737
  • 25
  • 73
  • 128
0

t and p are not initialized. If in the data, the 0th element has the maximum income or literacy, then t or p will be undefined and it will be accessing array elements out of bound. This can be confirmed by entering 0th state data with lower values than the subsequent states.

The solution is to initialize t and p to 0.

P.S. : Please indent your code. It is difficult to read. P.P.S. : max_lit should be float. P.P.P.S : Some error checking needs to be done (for eg. if n <= 50, etc).

jaychris
  • 121
  • 2