You have a few poblems
- You don't check the success of
malloc.
- You don't
malloc for person1->ads member.
- You don't check the success of
scanf.
This is a fixed and anotated version of your code
#include <stdio.h>
#include <stdlib.h>
struct address
{
int code;
char city[10];
};
struct student
{
char name[10];
struct address *ads;
};
int main()
{
/* You don't need te struct to be global, and it's generally a bad idea, not always of course */
struct student *person;
/* you should check that malloc succeeded otherwise undefined behavior would happen */
person = malloc(sizeof(*person));
if (person == NULL)
{
printf("cannot allocate memory\n");
return -1;
}
/* you should check that scanf succeeded too */
if (scanf("%9s", person->name) != 1)
/* ^ prevent buffer overflow */
{
printf("Invalid, input\n");
free(person);
return -1;
}
person->ads = malloc(sizeof(*(person->ads)));
if (person->ads == NULL)
{
printf("cannot allocate memory\n");
/* on failure free successfuly allocated person */
free(person);
return -1;
}
/* you should check that scanf succeeded too */
if (scanf("%d", &person->ads->code) != 1)
{
printf("Invalid, input\n");
free(person->ads);
free(person);
return -1;
}
/* you should check that scanf succeeded too */
if (scanf("%9s", person->ads->city) != 1)
/* ^ prevent buffer overflow */
{
printf("Invalid, input\n");
free(person->ads);
free(person);
return -1;
}
printf("Name: %s\n", person->name);
printf("Code: %d\n", person->ads->code);
printf("City: %s\n", person->ads->city);
free(person->ads);
free(person);
return 0;
}
adsa pointer in the first place. Just declare it instruct studentasstruct address ads;and populate it withperson1->ads..