C lecture 6.1
C lecture 6.1
Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a
structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information.
The ,struct keyword is used to define the structure.
Defining structure:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
struct employee
{
int id;
char name[20];
float salary;
};
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members or fields of the
structure.
Declaring structure variable:
We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:
By struct keyword within main() function
By declaring a variable at the time of defining the structure.
1st way: It should be declared within the main function.
struct employee
{
int id;
char name[50];
float salary;
};
Typedef vs #define:
typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values as
well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.
#include <stdio.h>
#include <string.h> // Example of type-def declaration
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( ) {
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "E Balaguruswamy");
strcpy( book.subject, "C Programming for Beginners");
book.book_id = 101;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
Nested Structure:
A structure can be nested inside another structure. In other words, the members of a structure can be of any other type including
structure. Here is the syntax to create nested structures.
structure tagname_1
{
member1;
member2;
member3;
...
membern;
structure tagname_2
{
member_1;
member_2;
member_3;
...
member_n;
}, var1
} var2;
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
e1.id=101;
strcpy(e1.name, "Sidharth Malhotra");
e1.doj.dd=16;
e1.doj.mm=01;
e1.doj.yyyy=1985;
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
Structures and functions:
We can pass structures as arguments to a function. In fact, we can pass, individual members, structure variables, a
pointer to structures etc. to the function. Similarly, functions can return either an individual member or structures
variable or pointer to the structure.