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];
CodePudding user response:
void main()
is wrong. It has to beint main(void)
- Here you have an example why hiding arrays behind the typedefs is a very bad habit. In your case pt[1] references the next array of two structs which outside the array bounds. You invoke undefined behaviour which can result in segfault.
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
{
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);
}
}