Initializing structures

Like other C variable types, structures can be initialized when they’re declared. This procedure is similar to that for initializing arrays. The structure declaration is followed by an equal sign and a list of initialization values is separated by commas and enclosed in braces. For example, look at the following statements for initializing the values of the members of the mysale structure variable.

struct sale {
char customer[20];
char item[20];
float amt;
} mysale = { "XYZ Industries",
“toolskit",
600.00
};

In a structure that contains structures as members, list the initialization values in order. They are placed in the structure members in the order in which the members are listed in the structure definition. Here’s an example that expands on the previous one:

struct customer {
char firm[20];
char contact[25];
}
struct sale {
struct customer buyer1;
char item [20];
float amt;
} mysale = {
{ "XYZ Industries", "Tyran Adams"},
"toolskit",
600.00
};

These statements perform the following initializations:

• the structure member mysale.buyer1.firm is initialized to the string “XYZ Industries”.
• the structure member mysale.buyer1.contact is initialized to the string “Tyran Adams”.
• the structure member mysale.item is initialized to the string “toolskit”.
• the structure member mysale.amount is initialized to the amount 600.00.

For example let us consider the following program where the data members are initialized to some value.

Write a program to access the values of the structure initialized with some initial values.

/* Program to illustrate to access the values of the structure initialized with some initial values*/
#include<stdio.h>
struct telephone{
int tele_no;
int cust_code;
char cust_name[20];
char cust_address[40];
int bill_amt;
};
main()
{
struct telephone tele = {2314345,
5463,
"Ram",
"New Delhi",
2435 };
printf("The values are initialized in this program.");
printf("\nThe telephone number is %d",tele.tele_no);
printf("\nThe customer code is %d",tele.cust_code);
printf("\nThe customer name is %s",tele.cust_name);
printf("\nThe customer address is %s",tele.cust_address);
printf("\nThe bill amount is %d",tele.bill_amt);
}

OUTPUT

The values are initialized in this program.
The telephone number is 2314345
The customer code is 5463
The customer name is Ram
The customer Address is New Delhi
The bill amount is 2435

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
?>