Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested structure in c

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);
    }
}
like image 524
AL-zami Avatar asked Mar 08 '16 14:03

AL-zami


2 Answers

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;
      ^^^^^^^^
};
like image 194
Vlad from Moscow Avatar answered Nov 15 '22 20:11

Vlad from Moscow


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
};
like image 27
ForceBru Avatar answered Nov 15 '22 21:11

ForceBru