How to get a variable of type struct town
?
struct town v ;
How to access it?
v.name[i] --> ith charcter of `name`
v.number
How to read them?
scanf("%s",v.name);
scanf("%u",&v.number);
Now how to access them from other struct?
In case you use pointer struct town *
you need something so that you can point to it. You need to gather some more variable which you can use to store your information.
struct town capital;// it doesn't need to point to anyone.
struct town* towns; // I need variable(s) of type struct town so that I can point to it.
towns= malloc(sizeof (struct town)* AS_MANY_AS_YOU_NEED);
//suppose you allocate for 4
you need to access them.
so what you do?
You can access each of these struct town type variable like this
town[i]
and then you can access them as I have shown before.
Do I need to allocate always more than 1 element?
Ofcourse not. You can have soething like
towns = malloc(sizeof (struct town));
access it like this towns[0]
or simply *(towns+0)
or *towns
What is allocating ?
Allocating memory to store something from free store of memory.
Help me more!!
Okay so you allocated some more variables in towns
i-th of which can be accessed like towns[i]
and
it's
name can be accessed like towns[i].name
.
number can be in towns[i].number
character of name
for a particular town towns[i].name[i]
How to access them from countries?
struct country {
char name[64]; //countries[i].name
struct town capital; //countries[i].capital.name or countries[i].capital.number
struct town *towns; // (countries[i]->towns[i]).name or ...
unsigned number_of_towns;
} countries[5];