Pointers
C Pointers  The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.  Consider the following example to define a pointer which stores the address of an integer.  int n = 10;  int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Declaring a pointer:  The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.  int *a;//pointer to int  char *c;//pointer to char Pointer Example: An example of using pointers to print the address and value is given below.
Example: #include<stdio.h> int main(){ int number=50; int *p; p=&number;//stores the address of number variable printf("Address of p variable is %x n",p); // p contains the a ddress of the number therefore printing p gives the address of number. printf("Value of p variable is %d n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p. return 0; } Output: Address of number variable is fff4 Address of p variable is fff4 Value of p variable is 50
Advantage of pointer 1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions. 2) We can return multiple values from a function using the pointer. 3) It makes you able to access any memory location in the computer's memory. Usage of pointer There are many applications of pointers in c language. 1) Dynamic memory allocation In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used. 2) Arrays, Functions, and Structures Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance. Address Of (&) Operator The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.
NULL Pointer: A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach. int *p=NULL; In the most libraries, the value of the pointer is 0 (zero).
Pointer Arithmetic in C: We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:  Increment  Decrement  Addition  Subtraction  Comparison
Incrementing Pointer in C: The Rule to increment the pointer is given below:  new_address= current_address + i * size_of(data typ e)  Where i is the number by which the pointer get increased.  32-bit  For 32-bit int variable, it will be incremented by 2 bytes.  64-bit  For 64-bit int variable, it will be incremented by 4 bytes.
Decrementing Pointer in C:  new_address= current_address - i * size_of(data type)  32-bit  For 32-bit int variable, it will be decremented by 2 bytes.  64-bit  For 64-bit int variable, it will be decremented by 4 bytes.
C Pointer Addition: We can add a value to the pointer variable. The formula of adding value to pointer is given below:  new_address= current_address + (number * size_of( data type))  32-bit  For 32-bit int variable, it will add 2 * number.  64-bit  For 64-bit int variable, it will add 4 * number.
C Pointer Subtraction:  new_address= current_address - (number * size_of(data type))  32-bit  For 32-bit int variable, it will subtract 2 * number.  64-bit  For 64-bit int variable, it will subtract 4 * number.
Illegal arithmetic with pointers: There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below.  Address + Address = illegal  Address * Address = illegal  Address % Address = illegal  Address / Address = illegal  Address & Address = illegal  Address ^ Address = illegal  Address | Address = illegal  ~Address = illegal
Pointer to function in C: Consider the following example to make a pointer pointing to the function. #include<stdio.h> int addition (); int main () { int result; int (*ptr)(); ptr = &addition; result = (*ptr)(); printf("The sum is %d",result); } int addition() { int a, b; printf("Enter two numbers?"); scanf("%d %d",&a,&b); return a+b; } Output: Enter two numbers?10 15 The sum is 25
Pointer to Array of functions in C: Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example: Program: #include<stdio.h> int show(); int showadd(int); int (*arr[3])(); int (*(*ptr)[3])(); int main () { int result1; arr[0] = show; arr[1] = showadd; ptr = &arr; result1 = (**ptr)(); printf("printing the value returned by show : %d",result1); (*(*ptr+1))(result1); } int show() { int a = 65; return a++; } int showadd(int b)
Generic Pointer:  When a pointer variable pointing to the type of void then it is known as Generic Pointer.  For example - void *ptr  ptr is a generic pointer  Since type void is not considered as data type so ptr does not point to any data type therefore it can not dereferenced.  For deferencing you have to type cast in specific data type
For example #include<stdio.h> int main() { int a = 10; void *ptr = &a; printf("%d", *(int *)ptr); return 0; }  ptr hold the address of integer variable but dereferncing we use type cast operator with int data type instead of above printf statement if we write  printf("%d", *ptr);  It will throw an error
C Double Pointer (Pointer to Pointer): The syntax of declaring a double pointer is given below. int **p; // pointer to a pointer which is pointing to an integer. Example: #include<stdio.h> void main () { int a = 10; int *p; int **pp; p = &a; // pointer p is pointing to the address of a pp = &p; // pointer pp is a double pointer pointing to the address of pointer p printf("address of a: %xn",p); // Address of a will be printed printf("address of p: %xn",pp); // Address of p will be printed printf("value stored at p: %dn",*p); // value stoted at the address contained by p i.e. 10 will be printed printf("value stored at pp: %dn",**pp); // value stored at the address contained by the pointer stoyred at pp } Output: address of a: d26a8734 address of p: d26a8738 value stored at p: 10 value stored at pp: 10
C Structure
C Structure: Why use structure?  In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches:  Construct individual arrays for storing names, roll numbers, and marks.  Use a special data structure to store the collection of different data types.
Program: #include<stdio.h> void main () { char names[2][10],dummy; // 2-dimensioanal character array names is used to store the names of the students int roll_numbers[2],i; float marks[2]; for (i=0;i<3;i++) { printf("Enter the name, roll number, and marks of the student %d",i+1); scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]); scanf("%c",&dummy); // enter will be stored into dummy character at each iteration } printf("Printing the Student details ...n"); for (i=0;i<3;i++) { printf("%s %d %fn",names[i],roll_numbers[i],marks[i]); } } Output Enter the name, roll number, and marks of the student 1Arun 90 91 Enter the name, roll number, and marks of the student 2Varun 91 56 Enter the name, roll number, and marks of the student 3Sham 89 69 Printing the Student details... Arun 90 91.000000 Varun 91 56.000000 Sham 89 69.000000
What is Structure: 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. Let's see the syntax to define the structure in c. struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; Let's see the example to define a structure for an entity employee in c. struct employee { int id; char name[20]; float salary; };
Example: Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members or fields of the structure. Let's understand it by the diagram given below:
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: 1. By struct keyword within main() function 2. By declaring a variable at the time of defining the structure. 1st way: Let's see the example to declare the structure variable by struct keyword. It should be declared within the main function. struct employee { int id; char name[50]; float salary; }; Now write given code inside the main() function. struct employee e1, e2; The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java. 2nd way: Let's see another way to declare variable at the time of defining the structure. struct employee { int id; char name[50]; float salary; }e1,e2;
Accessing members of the structure: There are two ways to access structure members: 1. By . (member or dot operator). 2. By -> (structure pointer operator).
Let's see another example of the structure in C language to store many employees information. #include<stdio.h> #include <string.h> struct employee { int id; char name[50]; float salary; }e1,e2; //declaring e1 and e2 variables for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array e1.salary=56000; //store second employee information e2.id=102; strcpy(e2.name, "James Bond"); e2.salary=126000; //printing first employee information printf( "employee 1 id : %dn", e1.id); printf( "employee 1 name : %sn", e1.name); printf( "employee 1 salary : %fn", e1.salary); //printing second employee information printf( "employee 2 id : %dn", e2.id); printf( "employee 2 name : %sn", e2.name); printf( "employee 2 salary : %fn", e2.salary); return 0; } Output: employee 1 id : 101 employee 1 name : Sonoo Jaiswal employee 1 salary : 56000.000000 employee 2 id : 102 employee 2 name : James Bond employee 2 salary : 126000.000000
Array of Structures:  An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structures.
Pass Structure to a Function By Value in C /* Passing Structure to a Function By Value */ #include <stdio.h> struct Student { char Student_Name[50]; float First_Year_Marks; float Second_Year_Marks; }; void PassBy_Value(struct Student Students); int main() { struct Student Student1; printf("nPlease Enter the Student Name n"); scanf("%s",&Student1.Student_Name); printf("nPlease Enter Student Inter First Year Marks n"); scanf("%f",&Student1.First_Year_Marks); printf("nPlease Enter Student Inter Second Year Marks n"); scanf("%f",&Student1.Second_Year_Marks); PassBy_Value(Student1); return 0; } void PassBy_Value(struct Student Students) { float Sum, Average; Sum = Students.First_Year_Marks + Students.Second_Year_Marks; Average = Sum/2; if(Average > 900) { printf("n %s is Eligible for Scholorship",Students.Student_Name); } else { printf("n %s is Not Eligible for Scholorship",Students.Student_Name); } } Output:
/* Passing Structure to function by reference */ #include <stdio.h> #include <string.h> struct Lecturer { char Lecturer_Name[50]; int Total_Experience; int Experience_In_This_College; }; void PassBy_Reference(struct Lecturer *Lecturers); int main() { struct Lecturer Lecturer1; printf("nPlease Enter the Lecturer Name n"); scanf("%s",&Lecturer1.Lecturer_Name); printf("Please Enter Lecturers Total Years of Experiencen"); scanf("%d",&Lecturer1.Total_Experience); printf("Enter Lecturers Total Years of Experience in this Collegen"); scanf("%d",&Lecturer1.Experience_In_This_College); PassBy_Reference(&Lecturer1); printf("n Lecturer Name = %s", Lecturer1.Lecturer_Name); printf("n Lecturers Total Years of Experience = %d", Lecturer1.Total_Experience); printf("n Years of Experience in this College = %d", Lecturer1.Experience_In_This_College); return 0; } void PassBy_Reference(struct Lecturer *Lecturers) { strcpy(Lecturers->Lecturer_Name, "Tutorial Gateway"); Lecturers->Total_Experience = 5; Lecturers->Experience_In_This_College = 3; } OUTPUT: Pass Structure to a Function By Reference in C Output:
Nested Structure in C:  C provides us the feature of nesting one structure within another structure by using which, complex data types are created.  For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code.  Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee.
Example: 1. #include<stdio.h> 2. struct address 3. { 4. char city[20]; 5. int pin; 6. char phone[14]; 7. }; 8. struct employee 9. { 10. char name[20]; 11. struct address add; 12. }; 13. void main () 14. { 15. struct employee emp; 16. printf("Enter employee information?n"); 17. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); 18. printf("Printing the employee information....n"); 19. printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,emp.add.city,emp.a dd.pin,emp.add.phone); 20. } Output Enter employee information? Arun Delhi 110001 1234567890 Printing the employee information.... name: Arun City: Delhi Pincode: 110001 Phone: 1234567890
The structure can be nested in the following ways. By separate structure By Embedded structure 1) Separate structure: Here, we create two structures, but the dependent structure should be used inside the main structure as a member. Consider the following example. struct Date { int dd; int mm; int yyyy; }; struct Employee { int id; char name[20]; struct Date doj; }emp1; As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures. 2) Embedded structure: The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be used in multiple data structures. Consider the following example. struct Employee { int id; char name[20]; struct Date {
Passing structure to function: Program: #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void display(struct employee); void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); display(emp); } void display(struct employee emp) { printf("Printing the details....n"); printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone); }
C Union:  Like structure, Union in c language is a user- defined data type that is used to store the different type of elements.  At once, only one member of the union can occupy the memory. In other words, we can say that the size of the union in any instance is equal to the size of its largest element.
Defining union: The union keyword is used to define the union. Let's see the syntax to define union in c. union union_name { data_type member1; data_type member2; . . data_type memeberN; }; Example to define union for an employee in c. union employee { int id; char name[50]; float salary; };
Example Program: 1. #include <stdio.h> 2. #include <string.h> 3. union employee 4. { int id; 5. char name[50]; 6. }e1; //declaring e1 variable for union 7. int main( ) 8. { 9. //store first employee information 10. e1.id=101; 11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array 12. //printing first employee information 13. printf( "employee 1 id : %dn", e1.id); 14. printf( "employee 1 name : %sn", e1.name); 15. return 0; 16. } Output: employee 1 id : 1869508435 employee 1 name : Sonoo Jaiswal
Enumeration:  An enumeration consists of integral constants. To define an enumeration, keyword enum is used.  enum flag { const1, const2, ..., constN };  Here, name of the enumeration is flag.  And, const1, const2,...., constN are values of type flag.  By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary). // Changing default values of enum enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3, };
Enumerated Type Declaration: When you create an enumerated type, only blueprint for the variable is created. Here's how you can create variables of enum type.  Here, a variable check of type enum boolean is created.  Here is another way to declare same check variable using different syntax. enum boolean { false, true }; enum boolean check; enum boolean { false, true } check;
Example: Enumeration Type #include <stdio.h> enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday }; int main() { enum week today; today = wednesday; printf("Day %d",today+1); return 0; } When you run the program, the output will be: Day 4
Why enums are used? Enum variable takes only one value out of many possible values. Example to demonstrate it, #include <stdio.h> enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3 } card; int main() { card = club; printf("Size of enum variable = %d bytes", sizeof(card)); return 0; } Output Size of enum variable = 4 bytes
 The output is 4 because the size of an integer is 4 bytes.  This makes enum a good choice to work with flags.  You can accomplish the same task using structures. However, working with enums gives you efficiency along with flexibility.
Example: include <stdio.h> enum designFlags { BOLD = 1, ITALICS = 2, UNDERLINE = 4 }; int main() { int myDesign = BOLD | UNDERLINE; // 00000001 // | 00000100 // ___________ // 00000101 printf("%d", myDesign); return 0; } Output 5

C Programming Unit-4

  • 1.
  • 2.
    C Pointers  Thepointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.  Consider the following example to define a pointer which stores the address of an integer.  int n = 10;  int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
  • 3.
    Declaring a pointer: The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.  int *a;//pointer to int  char *c;//pointer to char Pointer Example: An example of using pointers to print the address and value is given below.
  • 4.
    Example: #include<stdio.h> int main(){ int number=50; int*p; p=&number;//stores the address of number variable printf("Address of p variable is %x n",p); // p contains the a ddress of the number therefore printing p gives the address of number. printf("Value of p variable is %d n",*p); // As we know that * is used to dereference a pointer therefore if we print *p, we will get the value stored at the address contained by p. return 0; } Output: Address of number variable is fff4 Address of p variable is fff4 Value of p variable is 50
  • 5.
    Advantage of pointer 1)Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions. 2) We can return multiple values from a function using the pointer. 3) It makes you able to access any memory location in the computer's memory. Usage of pointer There are many applications of pointers in c language. 1) Dynamic memory allocation In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used. 2) Arrays, Functions, and Structures Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance. Address Of (&) Operator The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.
  • 6.
    NULL Pointer: A pointerthat is not assigned any value but NULL is known as the NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach. int *p=NULL; In the most libraries, the value of the pointer is 0 (zero).
  • 7.
    Pointer Arithmetic inC: We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:  Increment  Decrement  Addition  Subtraction  Comparison
  • 8.
    Incrementing Pointer inC: The Rule to increment the pointer is given below:  new_address= current_address + i * size_of(data typ e)  Where i is the number by which the pointer get increased.  32-bit  For 32-bit int variable, it will be incremented by 2 bytes.  64-bit  For 64-bit int variable, it will be incremented by 4 bytes.
  • 9.
    Decrementing Pointer inC:  new_address= current_address - i * size_of(data type)  32-bit  For 32-bit int variable, it will be decremented by 2 bytes.  64-bit  For 64-bit int variable, it will be decremented by 4 bytes.
  • 10.
    C Pointer Addition: Wecan add a value to the pointer variable. The formula of adding value to pointer is given below:  new_address= current_address + (number * size_of( data type))  32-bit  For 32-bit int variable, it will add 2 * number.  64-bit  For 64-bit int variable, it will add 4 * number.
  • 11.
    C Pointer Subtraction: new_address= current_address - (number * size_of(data type))  32-bit  For 32-bit int variable, it will subtract 2 * number.  64-bit  For 64-bit int variable, it will subtract 4 * number.
  • 12.
    Illegal arithmetic withpointers: There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below.  Address + Address = illegal  Address * Address = illegal  Address % Address = illegal  Address / Address = illegal  Address & Address = illegal  Address ^ Address = illegal  Address | Address = illegal  ~Address = illegal
  • 13.
    Pointer to functionin C: Consider the following example to make a pointer pointing to the function. #include<stdio.h> int addition (); int main () { int result; int (*ptr)(); ptr = &addition; result = (*ptr)(); printf("The sum is %d",result); } int addition() { int a, b; printf("Enter two numbers?"); scanf("%d %d",&a,&b); return a+b; } Output: Enter two numbers?10 15 The sum is 25
  • 14.
    Pointer to Arrayof functions in C: Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the following example: Program: #include<stdio.h> int show(); int showadd(int); int (*arr[3])(); int (*(*ptr)[3])(); int main () { int result1; arr[0] = show; arr[1] = showadd; ptr = &arr; result1 = (**ptr)(); printf("printing the value returned by show : %d",result1); (*(*ptr+1))(result1); } int show() { int a = 65; return a++; } int showadd(int b)
  • 15.
    Generic Pointer:  Whena pointer variable pointing to the type of void then it is known as Generic Pointer.  For example - void *ptr  ptr is a generic pointer  Since type void is not considered as data type so ptr does not point to any data type therefore it can not dereferenced.  For deferencing you have to type cast in specific data type
  • 16.
    For example #include<stdio.h> int main() { inta = 10; void *ptr = &a; printf("%d", *(int *)ptr); return 0; }  ptr hold the address of integer variable but dereferncing we use type cast operator with int data type instead of above printf statement if we write  printf("%d", *ptr);  It will throw an error
  • 17.
    C Double Pointer(Pointer to Pointer): The syntax of declaring a double pointer is given below. int **p; // pointer to a pointer which is pointing to an integer. Example: #include<stdio.h> void main () { int a = 10; int *p; int **pp; p = &a; // pointer p is pointing to the address of a pp = &p; // pointer pp is a double pointer pointing to the address of pointer p printf("address of a: %xn",p); // Address of a will be printed printf("address of p: %xn",pp); // Address of p will be printed printf("value stored at p: %dn",*p); // value stoted at the address contained by p i.e. 10 will be printed printf("value stored at pp: %dn",**pp); // value stored at the address contained by the pointer stoyred at pp } Output: address of a: d26a8734 address of p: d26a8738 value stored at p: 10 value stored at pp: 10
  • 18.
  • 19.
    C Structure: Why usestructure?  In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches:  Construct individual arrays for storing names, roll numbers, and marks.  Use a special data structure to store the collection of different data types.
  • 20.
    Program: #include<stdio.h> void main () { charnames[2][10],dummy; // 2-dimensioanal character array names is used to store the names of the students int roll_numbers[2],i; float marks[2]; for (i=0;i<3;i++) { printf("Enter the name, roll number, and marks of the student %d",i+1); scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]); scanf("%c",&dummy); // enter will be stored into dummy character at each iteration } printf("Printing the Student details ...n"); for (i=0;i<3;i++) { printf("%s %d %fn",names[i],roll_numbers[i],marks[i]); } } Output Enter the name, roll number, and marks of the student 1Arun 90 91 Enter the name, roll number, and marks of the student 2Varun 91 56 Enter the name, roll number, and marks of the student 3Sham 89 69 Printing the Student details... Arun 90 91.000000 Varun 91 56.000000 Sham 89 69.000000
  • 21.
    What is Structure: Structurein 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. Let's see the syntax to define the structure in c. struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; Let's see the example to define a structure for an entity employee in c. struct employee { int id; char name[20]; float salary; };
  • 22.
    Example: Here, struct isthe keyword; employee is the name of the structure; id, name, and salary are the members or fields of the structure. Let's understand it by the diagram given below:
  • 23.
    Declaring structure variable: Wecan 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: 1. By struct keyword within main() function 2. By declaring a variable at the time of defining the structure. 1st way: Let's see the example to declare the structure variable by struct keyword. It should be declared within the main function. struct employee { int id; char name[50]; float salary; }; Now write given code inside the main() function. struct employee e1, e2; The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java. 2nd way: Let's see another way to declare variable at the time of defining the structure. struct employee { int id; char name[50]; float salary; }e1,e2;
  • 24.
    Accessing members ofthe structure: There are two ways to access structure members: 1. By . (member or dot operator). 2. By -> (structure pointer operator).
  • 25.
    Let's see anotherexample of the structure in C language to store many employees information. #include<stdio.h> #include <string.h> struct employee { int id; char name[50]; float salary; }e1,e2; //declaring e1 and e2 variables for structure int main( ) { //store first employee information e1.id=101; strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array e1.salary=56000; //store second employee information e2.id=102; strcpy(e2.name, "James Bond"); e2.salary=126000; //printing first employee information printf( "employee 1 id : %dn", e1.id); printf( "employee 1 name : %sn", e1.name); printf( "employee 1 salary : %fn", e1.salary); //printing second employee information printf( "employee 2 id : %dn", e2.id); printf( "employee 2 name : %sn", e2.name); printf( "employee 2 salary : %fn", e2.salary); return 0; } Output: employee 1 id : 101 employee 1 name : Sonoo Jaiswal employee 1 salary : 56000.000000 employee 2 id : 102 employee 2 name : James Bond employee 2 salary : 126000.000000
  • 26.
    Array of Structures: An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structures.
  • 27.
    Pass Structure toa Function By Value in C /* Passing Structure to a Function By Value */ #include <stdio.h> struct Student { char Student_Name[50]; float First_Year_Marks; float Second_Year_Marks; }; void PassBy_Value(struct Student Students); int main() { struct Student Student1; printf("nPlease Enter the Student Name n"); scanf("%s",&Student1.Student_Name); printf("nPlease Enter Student Inter First Year Marks n"); scanf("%f",&Student1.First_Year_Marks); printf("nPlease Enter Student Inter Second Year Marks n"); scanf("%f",&Student1.Second_Year_Marks); PassBy_Value(Student1); return 0; } void PassBy_Value(struct Student Students) { float Sum, Average; Sum = Students.First_Year_Marks + Students.Second_Year_Marks; Average = Sum/2; if(Average > 900) { printf("n %s is Eligible for Scholorship",Students.Student_Name); } else { printf("n %s is Not Eligible for Scholorship",Students.Student_Name); } } Output:
  • 28.
    /* Passing Structureto function by reference */ #include <stdio.h> #include <string.h> struct Lecturer { char Lecturer_Name[50]; int Total_Experience; int Experience_In_This_College; }; void PassBy_Reference(struct Lecturer *Lecturers); int main() { struct Lecturer Lecturer1; printf("nPlease Enter the Lecturer Name n"); scanf("%s",&Lecturer1.Lecturer_Name); printf("Please Enter Lecturers Total Years of Experiencen"); scanf("%d",&Lecturer1.Total_Experience); printf("Enter Lecturers Total Years of Experience in this Collegen"); scanf("%d",&Lecturer1.Experience_In_This_College); PassBy_Reference(&Lecturer1); printf("n Lecturer Name = %s", Lecturer1.Lecturer_Name); printf("n Lecturers Total Years of Experience = %d", Lecturer1.Total_Experience); printf("n Years of Experience in this College = %d", Lecturer1.Experience_In_This_College); return 0; } void PassBy_Reference(struct Lecturer *Lecturers) { strcpy(Lecturers->Lecturer_Name, "Tutorial Gateway"); Lecturers->Total_Experience = 5; Lecturers->Experience_In_This_College = 3; } OUTPUT: Pass Structure to a Function By Reference in C Output:
  • 29.
    Nested Structure inC:  C provides us the feature of nesting one structure within another structure by using which, complex data types are created.  For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code.  Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee.
  • 30.
    Example: 1. #include<stdio.h> 2.struct address 3. { 4. char city[20]; 5. int pin; 6. char phone[14]; 7. }; 8. struct employee 9. { 10. char name[20]; 11. struct address add; 12. }; 13. void main () 14. { 15. struct employee emp; 16. printf("Enter employee information?n"); 17. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); 18. printf("Printing the employee information....n"); 19. printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,emp.add.city,emp.a dd.pin,emp.add.phone); 20. } Output Enter employee information? Arun Delhi 110001 1234567890 Printing the employee information.... name: Arun City: Delhi Pincode: 110001 Phone: 1234567890
  • 31.
    The structure canbe nested in the following ways. By separate structure By Embedded structure 1) Separate structure: Here, we create two structures, but the dependent structure should be used inside the main structure as a member. Consider the following example. struct Date { int dd; int mm; int yyyy; }; struct Employee { int id; char name[20]; struct Date doj; }emp1; As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures. 2) Embedded structure: The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be used in multiple data structures. Consider the following example. struct Employee { int id; char name[20]; struct Date {
  • 32.
    Passing structure tofunction: Program: #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void display(struct employee); void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone); display(emp); } void display(struct employee emp) { printf("Printing the details....n"); printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone); }
  • 33.
    C Union:  Likestructure, Union in c language is a user- defined data type that is used to store the different type of elements.  At once, only one member of the union can occupy the memory. In other words, we can say that the size of the union in any instance is equal to the size of its largest element.
  • 34.
    Defining union: The unionkeyword is used to define the union. Let's see the syntax to define union in c. union union_name { data_type member1; data_type member2; . . data_type memeberN; }; Example to define union for an employee in c. union employee { int id; char name[50]; float salary; };
  • 35.
    Example Program: 1. #include<stdio.h> 2. #include <string.h> 3. union employee 4. { int id; 5. char name[50]; 6. }e1; //declaring e1 variable for union 7. int main( ) 8. { 9. //store first employee information 10. e1.id=101; 11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array 12. //printing first employee information 13. printf( "employee 1 id : %dn", e1.id); 14. printf( "employee 1 name : %sn", e1.name); 15. return 0; 16. } Output: employee 1 id : 1869508435 employee 1 name : Sonoo Jaiswal
  • 36.
    Enumeration:  An enumerationconsists of integral constants. To define an enumeration, keyword enum is used.  enum flag { const1, const2, ..., constN };  Here, name of the enumeration is flag.  And, const1, const2,...., constN are values of type flag.  By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary). // Changing default values of enum enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3, };
  • 37.
    Enumerated Type Declaration: Whenyou create an enumerated type, only blueprint for the variable is created. Here's how you can create variables of enum type.  Here, a variable check of type enum boolean is created.  Here is another way to declare same check variable using different syntax. enum boolean { false, true }; enum boolean check; enum boolean { false, true } check;
  • 38.
    Example: Enumeration Type #include<stdio.h> enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday }; int main() { enum week today; today = wednesday; printf("Day %d",today+1); return 0; } When you run the program, the output will be: Day 4
  • 39.
    Why enums areused? Enum variable takes only one value out of many possible values. Example to demonstrate it, #include <stdio.h> enum suit { club = 0, diamonds = 10, hearts = 20, spades = 3 } card; int main() { card = club; printf("Size of enum variable = %d bytes", sizeof(card)); return 0; } Output Size of enum variable = 4 bytes
  • 40.
     The outputis 4 because the size of an integer is 4 bytes.  This makes enum a good choice to work with flags.  You can accomplish the same task using structures. However, working with enums gives you efficiency along with flexibility.
  • 41.
    Example: include <stdio.h> enum designFlags{ BOLD = 1, ITALICS = 2, UNDERLINE = 4 }; int main() { int myDesign = BOLD | UNDERLINE; // 00000001 // | 00000100 // ___________ // 00000101 printf("%d", myDesign); return 0; } Output 5