c - fgets 在函数内部获取结构指针崩溃

标签 c pointers struct

我在获取结构指针以通过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/

相关文章:

c - 传递指针: different value in stack?

c - 模拟 GCC 语句表达式

c - Malloc 是否分配了比需要的更多的内存?

电影院定时显示程序

C、帮助 while 循环在不为 true 时继续

c - 如何在 LLVM 中获取函数指针

使用 C 和指向指针的指针创建动态字符数组

c++ - 一般问题 : What to pass as pointer in C/C++?

c - 这是否会创建具有冒号后所写的相应大小的变量?

struct - rust:如何使用引用外部值的回调编写 `impl`