-
Structures nesting
Code:
#include<stdio.h>
int main()
{
struct address
{
char phone[15];
char city[25];
int pin;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e = {"jeru", "512455", "nagpur", 10};
printf(" %s %s\n", e.name, e.a.phone);
printf(" %s %d\n", e.a.city, e.a.pin);
return 0;
}
In the above program how the below statement occur:
Is that declared there ?
And my compiler gives two warning :
Code:
gcc -Wall -o "untitled5" "untitled5.c" (in directory: /home/duh/Desktop/C)
untitled5.c: In function ‘main’:
untitled5.c:15:9: warning: missing braces around initializer [-Wmissing-braces]
untitled5.c:15:9: warning: (near initialization for ‘e.a’) [-Wmissing-braces]
Compilation finished successfully.
-
The "struct address a" is a definition (which is a particular type of declaration) of a struct address as a member of struct emp.
To stop the compiler warning about missing braces, you need to add them in
Code:
struct emp e = {"jeru", {"512455", "nagpur", 10}};
The internal set of braces contains the initialisers for the struct address. What you have isn't strictly an error, but is an approach that is easy to mess up when initialising complicated structures - which is why compilers often emit (or can be configured to emit) a warning about it.
-
Pelles C give no warnings, and runs the program fine, as it was in #1. Grumpy's version is more strictly correct, however.
Unless the struct will ONLY be used in that function, it's much better to have the struct prototyped in global space, above main(), instead of inside it. Create the structs in main(), but define them outside it - that way every function can create local structs for their use, easily.
-
Thanks, that is clarified. :)