繁体   English   中英

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

[英]C code in Dev-Cpp breaks in runtime

我有一个如下的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

我可能误会了,但是您的代码中没有错误。 您的程序在return 0;退出就可以了return 0; main右后您输入的年龄。

输入年龄后,此函数将立即返回

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM