Dev-Cpp中的C代码在运行时中断

nam*_*mco 1 c struct pointers

我有一个像下面的C代码.

#include <stdio.h>
#include <stdlib.h>
struct __student{
    char name[20];
    char surname[20];
    int age;
};

typedef struct __student student;

void getStudent(student* stud)
{
    printf("Name: "); scanf("%s",stud->name);
    printf("Surname: "); scanf("%s",stud->surname);
    printf("Age: "); scanf("%d",stud->age);
}

int main(int argc, char *argv[]) 
{
    student* s = (student*)malloc(sizeof(student));
    getStudent(&s);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此代码在Dev Cpp 5.10中编译时没有任何错误或警告.
但是当我尝试运行这个应用程序时,它在我输入年龄值后就会中断.
我不明白是什么问题?

Ale*_*íaz 6

你正在传递一个student**(这是一个指向指针的指针)你的函数期望a student*,它也会发出警告(至少在GCC 4.9.2上)

将您的代码更改为

int main(int argc, char *argv[]) 
{
    student* s = malloc(sizeof(student)); //also don't cast the malloc
    getStudent(s);
    free(s); //we don't want memory leaks
    return 0;
}
Run Code Online (Sandbox Code Playgroud)