我在获取结构指针
以通过c程序中的函数内的fgets
获取用户输入时遇到问题;我不确定我做错了什么。 getInput()
函数是发生崩溃的地方。我首先尝试将内存分配给要存储名称的位置
*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);
}
最佳答案
你的分配是错误的。真正的分配是这样的;
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 *) 也是不必要的。
关于c - fgets 在函数内部获取结构指针崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179703/