I have to build a nested structure to store some basic information about some person (name, age, address). So I created a structure called "info" and to hold the address I created another nested structure inside "info" called "address". But whenever I prompt to store the values using a for loop, I get errors. What is the problem here and how can I solve it?
[Error] 'struct Info' has no member named 'address'
[Warning] declaration does not declare anything [enabled by default]
#include <stdio.h>
int main(){
struct Info{
char name[30];
int age;
struct address{
char area_name[39];
int house_no;
char district[39];
};
};
struct Info Person[10];
int i;
for(i=0;i<10;i++){
printf("enter info of person no %d\n",i);
printf("enter name\n");
scanf("%s",&Person[i].name);
printf("enter age\n");
scanf("%d",&Person[i].age);
printf("enter address :\n");
printf("enter area name :\n");
scanf("%s",&Person[i].address.area_name);
printf("enter house no : \n");
scanf("%d",&Person[i].address.house_no);
printf("enter district : \n");
scanf("%s",&Person[i].address.district);
}
}
You declared a type struct address
in the structure Info
but not a data member of this type.
You can write for example
struct Info{
char name[30];
int age;
struct address{
char area_name[39];
int house_no;
char district[39];
} address;
^^^^^^^^
};
What you have at the moment is just a declaration of a structure called address
, but you'll need a variable called address
in struct Info
to use the Person[i].address
syntax.
What you need is to move the word address
a bit:
struct Info{
char name[30];
int age;
struct {
char area_name[39];
int house_no;
char district[39];
} address; // <<< here it is now
};
Another option is to use the following:
struct Info{
char name[30];
int age;
struct addr{ // as noted by @JonathanLeffler,
// it's not necessary to change the
// name of a struct
char area_name[39];
int house_no;
char district[39];
};
struct addr address; // <<< a variable of type struct addr
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With