2016-12-16 76 views
0

我在获取struct pointer以通过fgets在c程序中的函数内部执行用户输入时遇到问题;我不确定我做错了什么。功能getInput()是发生崩溃的地方。我首先尝试在那里的名称将被存储与fgets在函数崩溃时使用结构指针

*stu->name = (char*)malloc(N_LENGTH); 

然后第一线,也是在得到来自用户的输入与

fgets(*stu->name, N_LENGTH, stdin); 

程序崩溃内存分配给第二行。

对不起,如果我打破任何规则,因为这是我第一次在网站上。

代码:

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

#define UNIT 100 
#define HOUSE 1000 
#define THRESH 12 
#define DISCOUNT 10 
#define NUM_PERSONS 5 
#define N_LENGTH 30 


struct student 
{ 
    char *name; 
    char campus; 
    int userUnit; 
}; 

void getInput(struct student *stu); 
int amountCalc(struct student *stu); 
void printOutput(struct student stu, int total); 

int main() 
{ 
    int total[NUM_PERSONS]; 
    int averageTotal=0; 
    struct student tempStudent; 
    struct student students[NUM_PERSONS]; 
    struct student *sPtr = &tempStudent; 
    int i; 
    for (i=0; i < NUM_PERSONS; i++) 
    { 
     getInput(sPtr); 
     students[i]=tempStudent; 
     total[i]=amountCalc(sPtr); 
     averageTotal+=total[i]; 
    }; 

    for (i=0; i < NUM_PERSONS; i++) 
    { 
     printOutput(students[i], total[i]); 
    }; 

    printf("\nThe average tuition cost for these %d students is $%.2f.\n", 
      NUM_PERSONS, averageTotal/(NUM_PERSONS*1.0)); 
    return 0; 
} 

void getInput(struct student *stu) 
{ 
     fflush(stdin); 
     printf("Enter student name: "); 
     *stu->name = (char*)malloc(N_LENGTH); 
     fgets(*stu->name, N_LENGTH, stdin); 

     printf("Enter y if student lives on campus, n otherwise: "); 
     scanf(" %s", &stu->campus); 

     printf("Enter current unit count: "); 
     scanf(" %d", &stu->userUnit); 

     printf("\n"); 
} 

int amountCalc(struct student *stu) 
{ 
     int total; 
     total=(stu->userUnit)*UNIT; 

     if (stu->userUnit>THRESH) { 
      total-=((stu->userUnit)-12)*DISCOUNT; 
     }; 

     if (stu->campus=='y') { 
      total+=HOUSE; 
     }; 
     return total; 
} 

void printOutput(struct student stu, int total) 
{ 
    printf("\nStudent name: %s\n", stu.name); 
    printf("Amount due: $%d\n\n", total); 
} 
+1

'* stu-> name' - >'stu-> name'。 –

+1

不要忽略编译器警告。 –

回答

0

你的配置是错误的。真正的分配是这样的;

void getInput(struct student *stu) 
{ 
    fflush(stdin); 
    printf("Enter student name: "); 
    stu->name = (char*)malloc(N_LENGTH); 
    fgets(stu->name, N_LENGTH, stdin); 

    printf("Enter y if student lives on campus, n otherwise: "); 
    scanf(" %s", &stu->campus); 

    printf("Enter current unit count: "); 
    scanf(" %d", &stu->userUnit); 

    printf("\n"); 
} 

当你编译它时,你可以看到一个警告。你应该照顾所有的警告。并且将malloc转换为(char *)也是不必要的。

-1

请勿使用fflush(stdin)See this question.我不知道是否会导致错误,但它没有在C标准中定义,所以也许你的平台无法处理它!

错误的内存分配也是一个问题,请看@HakkıIşık的答案。