[英]Segmentation fault (core dumped) in C
Code attached below.下面附上代码。 I tried to run the code, the values printed are correct but getting segmentation fault.我尝试运行代码,打印的值是正确的,但出现分段错误。 Can anyone explain why?谁能解释为什么?
#include <stdio.h>
typedef struct
{
char name[30];
int age;
} rec[2];
void main()
{
rec g;
rec *pt = &g;
for (int i = 0; i < 2; i++)
{
printf("Enter name: ");
scanf("%s", &pt[i]->name);
printf("Enter age: ");
scanf("%d", &pt[i]->age);
}
printf("Name\tAge\n");
for (int i = 0; i < 2; ++i)
{
printf("%s\t", pt[i]->name);
printf("%d\n", pt[i]->age);
}
And also please explain the difference between也请解释两者之间的区别
typedef struct {
int a;
} example[3];
example v;
and和
typedef struct {
int a;
} example;
example v[3];
void main()
is wrong. void main()
是错误的。 It has to be int main(void)
它必须是int main(void)
You need to:你需要:
typedef struct
{
char name[30];
int age;
} rec[2];
int main()
{
rec g;
rec *pt = &g;
for (int i = 0; i < 2; i++)
{
printf("Enter name: ");
scanf("%s", pt[0][i].name);
printf("Enter age: ");
scanf("%d", &(pt[0][i].age));
}
printf("Name\tAge\n");
for (int i = 0; i < 2; ++i)
{
printf("%s\t", pt[0][i].name);
printf("%d\n", pt[0][i].age);
}
}
The best way is to typedef struct and define the array.最好的方法是 typedef struct 并定义数组。
typedef struct
{
char name[30];
int age;
} rec;
int main()
{
rec pt[2];
for (int i = 0; i < 2; i++)
{
printf("Enter name: ");
scanf("%s", pt[i].name);
printf("Enter age: ");
scanf("%d", &(pt[i].age));
}
printf("Name\tAge\n");
for (int i = 0; i < 2; ++i)
{
printf("%s\t", pt[i].name);
printf("%d\n", pt[i].age);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.