Declaration of structure variable
We can declare structure variables in different ways.
Declaring structure variable along with structure declaration
Syntax
struct name/tag { //structure members } variables;
Example
struct car { char name[100]; float price; } car1;
We can also declare many variables using comma (,) like below,
Example
struct car { char name[100]; float price; } car1, car2, car3;
Declaring structure variable using struct keyword.
Syntax
struct name variables;
Example
struct car { char name[100]; float price; }; struct car car1, car2, car3;
In general, we declare variables like,
<data type> variables;
Example
int i; float f;
In structure, data type is <struct name>. So, the declaration will be
<struct name> variables;
Example
struct car car1;
Initializing structure members
We can initialize the structrue members directly like below,
Example
struct car { char name[100]; float price; }; //car1 name as "xyz" //price as 987432.50 struct car car1 ={"xyz", 987432.50};
How to access the structure members?
To access structure members, we have to use dot (.) operator.
It is also called the member access operator.
To access the price of car1,
car1.price
To access the name of car1,
car1.name
Sample Program
Example
#include<stdio.h> int main() { struct car { char name[100]; float price; }; // car1.name -> "xyz" //car1.price -> 987432.50 struct car car1 ={"xyz", 987432.50}; //printing values using dot(.) or 'member access' operator printf("Name of car1 = %s\n",car1.name); printf("Price of car1 = %f\n",car1.price); return 0; }
We can also change the value of structure members using dot (.) operator or member access operator
Sample program
Example
#include<stdio.h> int main() { struct car { char name[100]; float price; }; // car1.name -> "xyz" //car1.price -> 987432.50 struct car car1 ={"xyz", 987432.50}; //changing car1 price car1.price = 1000000.50; printf("Price of car1 = %f\n",car1.price); //output will be 1000000.50 return 0; }