0

当我运行下面的代码来查找最大识字率和最大收入时,程序正在正确输入,但最后在显示最后两个 printf 语句的输出时,我收到以下错误“segmentation fault.core dumped”。请解释什么是错的..提前谢谢。

#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;
}
4

3 回答 3

0

线

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

应该

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

因为说明符%s正在寻找char*并且您正在尝试通过char (*)[50].

于 2013-10-28T05:38:33.577 回答
0

不要scanf用于字符串,而是使用fgets(s[i].name,50,stdin)

因为scanf cannot read spaces in a string. 假设您输入hello world虽然大小小于 50,但它只hello考虑并且world不存储在字符串中,因为一旦space character检测到字符串读取被终止scanf

如果第 0 个元素本身就是最大的识字率和收入,则 t 和 p 值也必须初始化为 0。的价值t and p are garbage values

阅读它们以了解为什么不&用于在 scanf 中读取字符串

C:为什么 scanf() 函数中的字符串没有 &?

当前面定义的字符串数组的第一个字符串为 null 时,scanf() 不读取输入字符串

为什么我们不在scanf中使用'&'作为char数组

使用 scanf 读取字符串

于 2013-10-28T05:40:05.587 回答
0

t 和 p 未初始化。如果在数据中,第 0 个元素的收入或识字率最高,则 t 或 p 将是未定义的,它将越界访问数组元素。这可以通过输入值低于后续状态的第 0 个状态数据来确认。

解决方案是将 t 和 p 初始化为 0。

PS:请缩进你的代码。很难阅读。PPS:max_lit 应该是浮动的。PPPS:需要进行一些错误检查(例如,如果 n <= 50 等)。

于 2013-10-28T05:40:28.570 回答