2012-12-04 72 views
0

這是基於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編譯器。和常見的文本編輯器。

回答

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]; 
1

還有就是你的問題:

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

您在字符串進行掃描,但你的變量隻字符:

char firstName; 
    char lastName; 
    char middleName; 
1

我想你可能想爲您的數據提供一個緩衝

char firstName[SOME_BIG_ENOUGH_SIZE]; 

而不是單個字符:

char firstName;