Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other datatype. Structure variables can be declared in following two ways:
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type.
Example:-
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
};
int main()
{
struct Student s1; // s1 is a variable of Student type and
s1.age = 53; //age is a member of Student
strcpy(s1.name, "Rupesh"); //using string function to add name
printf("Name of Student : %s\n", s1.name); //displaying the stored values
printf("Age of Student : %d\n", s1.age);
return 0;
}
Output:-
Name of Student : Rupesh
Age of Student : 53
Array of Structure
We can also declare an array of structure variables. in which each element of the array will represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
Example:-
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
struct Employee emp[5];
int i, j;
void ask()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{
ask();
}
Typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
Syntax:-
typedef <existing_name> <alias_name>


0 Comments