Dev Cpp中的C代码在运行时中断
我有一个C代码如下Dev Cpp中的C代码在运行时中断,c,pointers,struct,C,Pointers,Struct,我有一个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->nam
#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;
}
#包括
#包括
学生结构{
字符名[20];
查氏[20];
智力年龄;
};
类型定义结构u学生;
无效getStudent(学生*螺柱)
{
printf(“名称:”;scanf(“%s”,螺柱->名称);
printf(“姓氏:”;scanf(“%s”,螺柱->姓氏);
printf(“年龄:”;scanf(“%d”,螺柱->年龄);
}
int main(int argc,char*argv[])
{
学生*s=(学生*)malloc(学生人数);
getStudent&s;
返回0;
}
此代码在Dev Cpp 5.10中编译时没有任何错误或警告。但当我尝试运行此应用程序时,它在我输入年龄值后中断。
我不明白是什么问题 我可能误解了,但您的代码中没有错误。当程序到达
返回0时退出是可以的输入年龄后立即在main
中输入code>
在这里,函数在您输入年龄后立即返回
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)代码>我可能误解了,但您的代码中没有错误。当程序到达返回0时退出是可以的输入年龄后立即在main
中输入code>
在这里,函数在您输入年龄后立即返回
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)代码>您正在传递一个学生**
(即指向指针的指针),其中您的函数需要一个学生*
,并且它确实会发出警告(至少在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**
(即指向指针的指针),其中您的函数需要一个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;
}
除了通过正确的学生
,如上述答案所述
printf("Age: "); scanf("%s=d",stud->age);
应该是
printf("Age: "); scanf("%d", &stud->age);
当您键入一个分配给int
的数字时,除了要传递正确的学生
,如上所述
printf("Age: "); scanf("%s=d",stud->age);
应该是
printf("Age: "); scanf("%d", &stud->age);
当您键入一个分配给int
的数字时,他的代码中有错误。您的答案是错误的。@self,对不起,我没有看到这个。是的,他的代码中有错误。你的答案是错的。@self,对不起,我没有看到这个。