Nested structure in c

AL-zami picture AL-zami · Mar 8, 2016 · Viewed 10.8k times · Source

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);
    }
}

Answer

Vlad from Moscow picture Vlad from Moscow · Mar 8, 2016

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;
      ^^^^^^^^
};