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



我有一个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;
}

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

您正在传递一个student**(这是一个指向指针的指针),而您的函数期望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;
}

除了如上所述通过正确的student外,

printf("Age: "); scanf("%s=d",stud->age);

应该是

printf("Age: "); scanf("%d", &stud->age);

当您键入一个分配给int的数字时。

我可能误解了,但您的代码中没有错误。当你进入年龄后,你的程序在main中达到return 0;时退出是可以的。

在这里,功能在您输入年龄后立即返回

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

在这里,您呼叫getStudent,然后返回0

student* s = (student*)malloc(sizeof(student));
getStudent(&s); // that's incorrect!!
free(s); //remove this if you're using s after this call
return 0;
}

哦,是的!没早点收到,对不起您必须使用getStudent(s);而不是getStudent(&s);

最新更新