FOR循环时的分段故障(核心转储)

时间:2012-12-04 13:33:07

标签: c

这是C:

上的代码

这是功能:

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

struct worker
{
    char firstName;
    char lastName;
    char middleName;
    int age;
    float height;
};

void enterData();
void displayData();
void makeCalc();

struct worker *b;
int count;

int main(void)
{
    enterData();
    displayData();
    makeCalc();
    free(b);
    return 0;
}

void enterData()
{
    char firstName;
    char lastName;
    char middleName;
    int age;
    float height;


    printf("Количество работников: \n");
    scanf("%d", &count);

    if(count <= 0){
        exit(0);
    }

    b = (struct worker *)malloc(count*sizeof(struct worker));


    for(int i = 0; i<count; i++){
        printf("Введите имя, фамилию, отчестве, возраст и рост через пробел: \n");
        scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);
        struct worker a = (struct worker) {firstName, lastName, middleName, age, height};
        b[i] = a;
    }

}

如果程序显示为Segmentation fault (core dumped)

,则此部分的运行时
for(int i = 0; i<count; i++){
            printf("Enter name, surname and middle name: \n");
            scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);
            struct worker a = (struct worker) {firstName, lastName, middleName, age, height};
            b[i] = a;

这可能是什么原因?我是C的新手;

P.S我在ubuntu 12.04上使用GCC编译器。和普通的文本编辑器。

3 个答案:

答案 0 :(得分:1)

有你的问题:

    scanf("%s%s%s%d%f", &firstName, &lastName, &middleName, &age, &height);

您扫描字符串,但您的变量只是字符:

   char firstName;
   char lastName;
   char middleName;

答案 1 :(得分:1)

我想您可能想为您的数据提供缓冲区

char firstName[SOME_BIG_ENOUGH_SIZE];

而不是单个字符:

char firstName;

答案 2 :(得分:0)

问题是您在声明中使用char类型并在scanf中使用%s

必须将这些更改为保存字符串

 char firstName;
 char lastName;
 char middleName;

应改为

char firstName[MAX]; //where MAX is any convenient high value.
char lastName[MAX];
char middleName[MAX];