















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
The concept of structures and unions in C programming language. It describes how structures can be used to group variables of different data types under a single name. It also explains the features of structures, how to declare and access structure variables, and how to perform operations on individual members of a structure. examples and syntax for better understanding of the topic.
Typology: Study Guides, Projects, Research
1 / 23
This page cannot be seen from the preview
Don't miss anything!
Structures and Unions Introduction:
We have seen that an array can be used to represent a group of data items that belong to the same type, such as int or float. An array can store many values of similar data type. In real life we need to have different data types for example to maintain employees information we should have information such as name, age, qualification, salary etc. Here to maintain the information of employees dissimilar data types are required. All these types cannot be expressed in a single array. One may think to declare different arrays for each data type. But there will be huge increase in source code of the program. Hence, arrays cannot be useful here. C supports a constructed data type known as structures.
Definition: A structure is a collection of one or more variables , of different data types , grouped together under a single name. By using structures we can make a group of variables arrays, pointers etc. Let us use an example to illustrate the process of structure definition & creation of structure variables. Consider a book database consisting of book name, author, number of pages and price. We can define a structure to hold this information.
struct book_name { char title[20]; char author[15]; int pages; float price; };
The keyword struct declares a structure to hold the details of 4 data fields, namely title, author, pages and price. These fields are called structure elements or members. Each member may belong to a different type of data. book_bank is the name of the structure and is called the structure tag.
The tag name may be used subsequently to declare variables that have the tag’s structure. Note that the above definition has not declared any variables. It simply describes a format called template to represent information as shown below.
title array of 20 chars author array of 15 chars pages integer price float
The general format of a structure
struct tag_name { data_type member1; data_type member2;
}; In defining a structure you may note the following syntax.
The template is terminated with a semicolon.
While the entire definition is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. The tag name such as book_bank can be used to declare structure variable of its type, later in the program.
Features of Structures:
To copy elements of one array to another array of same data type elements are copied one by one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the contents of all structure elements of different data types to another structure variable of its type using assignment (=) operator. It is possible because structure elements are stored in successive memory locations. Nesting of structures is possible i.e. one can create structure within the structure. Using this feature one can handle complex data types. It is possible to pass structure elements to a function. This is similar to passing an ordinary variable to a function. One can pass individual structure elements (or) entire structure by value (or) address. It is also possible to create structure pointers. We can also create a pointer pointing to structure elements. For this we require “->‟ operator.
Arrays vs Structures:
Both the arrays and structures are classified as structured data types as they provide a mechanism that enable us to access and manipulate data in a relatively easy manner.
An array is a collection of related data elements of same type. Structure can have elements of different types. An array is derived data type whereas a structure is a programmer-defined one. Any array behaves like a built-in-data type. All we have to do is to declare an array variable and use it. But in the case of a structure, first we have to design and declare a data structure before the variables of that type are declared and used.
Declaring structure variables:
After defining a structure format we can declare variables of that type. A structure variable declaration is similar to the declaration of variable of any data types.
The keyword struct. The structure tag name. List of variable names separated by commas. A terminating semicolon.
For Ex: struct book_bank book1, book2, book3;
The above example declares book1, book2, book3 as variables of type struct book_bank. Each one of these variables has four members as specified by the template.
struct book_bank { char title[20]; char author[15]; int pages; float price; };
The following statements initialize two structure variables. Here, it is essential to use a tag name.
main() { struct st_record { int weight; float height; }; struct st_record student1={60,180.75}; struct st_record student2={53,170.60};
}
Another method is to initialize a structure variable outside the function.
struct st_record { int weight; float height; }student1={60,180.75};
main() { struct st_record student2={53,170.60};
}
C language does not permit the initialization of individual structure members within the template. The initialization must be done only in the declaration of the actual variables.
Compile time initialization of structure variable must have following elements.
The keyword struct The structure tag name The name of the variable to be declared The assignment operator = A set of values for the members of the structure variable, separated by commas and enclosed in braces. A terminating semicolon
Rules for initializing structures:
We cannot initialize individual members inside the structure template. The order of values enclosed in braces must match the order of members in the structure definition. It is permitted to have partial initialization. we can initialize only the first few members and leave the remaining blank. The uninitialized members should be only at the end of the list. The uninitialized members will be assigned default values as follows.
zero for integer and floating point numbers. '\0' for character strings.
Accessing Structure members:
We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. For example, the word title has no meaning. The link between a member and a variable is established using the member operator ‘.’ which is also known as dot operator or period operator.
Ex : book1.price
Is the variable representing the price of book1 and can be treated like any other ordinary variable. Here is how we would assign values to the members of book1.
strcpy(book1.title,”BASIC”); strcpy(book1.author,”Balagurusamy”); book1.pages=250; book1.price=120.50; Use scanf to give the values through keyboard. scanf(“%s”,book1.title); scanf(“%d”,&book1.pages);
#include<stdio.h> #include<conio.h> struct personal { char name[20]; int day; char month[10]; int year; float salary; }; main() { struct personal person; printf(“Input Values”); scanf(“%s%d%s%d%f”,person.name,&person.day,person.month, &person.year,&person.salary); printf(“%s%d%s%d%f”,person.name,person.day,person.month,person.ye ar,person.salary); } OUTPUT : Input values akshaya 19 july 1988 4500 akshaya 19 july 1988 4500.
We can also apply the increment and decrement operators to numeric type members. For
example, the following statements are valid:
stu1.no++; ++ stu2.no;
Example: C Program to Store Information (name, roll and marks) of a Student Using Structure #include <stdio.h> struct student { char name[50]; int roll; float marks; }; main() { struct student s; printf("Enter information of students:\n\n"); printf("Enter name: "); scanf("%s",s.name); printf("Enter roll number: "); scanf("%d",&s.roll); printf("Enter marks: "); scanf("%f",&s.marks); printf("\nDisplaying Information\n"); printf("Name: %s\n",s.name); printf("Roll: %d\n",s.roll); printf("Marks: %.2f\n",s.marks); } Output: Enter information of students: Enter name: Adele Enter roll number: 21 Enter marks: 334. Displaying Information name: Adele Roll: 21 Marks: 334. Structures within Structures (or) Nested Structures:
Structure with in a structure means nesting of structures. Nesting of structures is permitted in c.
Ex: struct salary { char name; char department; int basic_pay; int dearness_allowance; int house_rent_allowance; int city_allowance; }employee;
This structure defines name, department, basic pay and 3 kinds of allowances. We can group all the items related to allowance together and declare them under a substructure as shown.
struct salary { char department; char name; int basic_pay; struct { int dearness; int house_rent; int city; }allowance; }employee;
It is also permissible to nest more than one type of structures
struct personal_record { struct name_part name; struct addr_part address; struct date date_of_birth;
}; struct personal_record person1;
The first member of this structure is name, which is of the type struct name_part,other members have their structure types.
Example: #include <stdio.h> struct Employee { char ename[20]; int ssn; float salary; struct date { int date; int month; int year; }doj; }emp = {"Pritesh",1000,1000.50,{22,6,1990}}; int main() { printf("\nEmployee Name : %s",emp.ename); printf("\nEmployee SSN : %d",emp.ssn); printf("\nEmployee Salary : %f",emp.salary); printf("\nEmployee DOJ : %d/%d/%d", emp.doj.date,emp.doj.month,emp.doj.year); } Output : Employee Name : Pritesh
#include<stdio.h> struct marks { int eng; int tel; int sci; int tot; }; main( ) { int i; struct marks student[3]={{45,67,81,0},{75,53,69,0},{57,36,71,0}}; struct marks t={0,0,0,0}; clrscr(); for(i=0;i<3;i++) { student[i].tot=student[i].eng+student[i].tel+student[i].sci; t.eng=t.eng+student[i].eng; t.tel=t.tel+student[i].tel; t.sci=t.sci+student[i].sci; t.tot=t.tot+student[i].tot; } printf(" STUDENT TOTAL \n\n"); for(i=0;i<3;i++) printf("stu[%d] : %d\n",i+1,student[i].tot); printf("SUBJECT TOTAL\n\n"); printf("English:%d\nTelugu:%d\nScience :%d\n",t.eng,t.tel,t.sci); printf("\n Grand total : %d\n",t.tot); getch( ); }
Arrays with in structures:
C Permits the use of arrays as structure members. We have already used arrays of characters inside a structure. Similarly, we can use single-dimensional or multi dimensional arrays of type int or float. Ex : struct marks { int number; float subject[3]; }student[2];
Here, the member subject contains 3 elements, subject[0],subject[1]&subject[2].These elements can be accessed using appropriate subscripts. For Ex: student[1].subject[2]; Would refer to the marks obtained in the 3rd^ subject by the 2nd^ student. Example: Rewrite the program of above example 1 using an array member to represent the three subjects. #include<stdio.h> main( ) { struct marks {
int sub[3]; int total; }; struct marks student[3]= {10,20,30,0,10,20,30,0,10,20,30,0}; struct marks t={0,0,0,0}; int i,j,k=0; clrscr(); for(i=0;i<=2;i++,k++) /* „i represent student/ { for(j=0;j<=2;j++) / „j represent subjects */ { student[i].total+=student[i].sub[j]; t.sub[i]+=student[i].sub[i]; }
t. total+= student[i].total; }
printf("\nSTUDENT TOTAL\n\n"); for(i=0;i<=2;i++) printf("student[%d] %d\n", i+1,student[i].total); printf("\nSUBJECT TOTAL\n\n"); for(k=0;k<=2;k++) printf("subject-%d\t %d\n",k+1,t.sub[k]); printf("\nGrand Total = %d\n", t.total); getch();} Structures and functions :
It is natural that C supports the passing of structure values as arguments to functions. There are 3 methods by which by which the values of a structure can be transferred from one function to another.
#include<stdio.h> #include<conio.h> struct boy { char name[25]; int age; int wt; }; void main() { struct boy b1={“Amit”,20,25}; clrscr(); print(b1.name,b1.age,b1.wt); } print(char *s,int t,int n); { printf(“%s%d%d”,s,t,n); return 0;
Pointers and Structures:
We know that the name of an array stands for the address of its zeroth element. The same thing is true of the names of arrays of structure variables. Suppose product is an array variable of struct type. The name product represents the address of its zeroth element.
Consider the following declaration:
struct inventory { char name[30]; int number; float price; }product[2], *ptr;
This statement declares product as an array of two elements, each of the type struct inventory and ptr as a pointer to data objects of the type struct inventory. The assignment
ptr = product;
would assign the address of the zeroth element of product to ptr. That is, the pointer will now point to product[0]. Its members can be accessed using the following notation.
ptr -> name ptr -> number ptr -> price The symbol -> is called the arrow operator (also known as member selection operator ) and is made up of a minus sign and a > sign. Note that ptr -> is simply another way of writing product[0].
When the pointer ptr is incremented by one, it is made to point the next record, i.e. product[1]. The following for statement will print the values of members of all the elements of product array.
for(ptr = product; ptr < product+2; ptr++) printf(“%s%d%f\n”,ptr->name,ptr->number,ptr->price);
We could also use the notation
(*ptr).number
To access the member number, The parentheses around *ptr are necessary because the member operator ‘.’ Has a higher precedence the operator *
Ex: Program to declare pointer to structure and display the contents of the structure.
#include<stdio.h> #include<conio.h> struct book { char name[25]; char author[25]; Int pages; }; void main()
struct book b1={“Let us C”,”Balagurusamy”,886}; struct book *ptr; ptr=&b1; clrscr(); printf(“%s by %s of %d pages”,b1.name,b1.author,b1.pages); printf(“%s by %s of %d pages”,ptr->name,ptr->author,ptr->pages); } Output :
Let us C by Balaguruswamy of 886 pages Let us C by Balaguruswamy of 886 pages
Unions:
Unions are a concept borrowed from structures and therefore follow the same syntax as structure. However the major distinction between them in terms of storage. In structures, each member has its own storage location, whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only once member at a time. Like structures, a union can be declared using the keyword union as fallows
union book { char title; char author; int pages; float price; }book1;
The union requires bytes that are equal to the number of bytes required for the largest members. For Ex: this union contain char, float, int then the number of bytes reserved in the memory for the union is 4 bytes.
price title,author
pages
To access a union member, we can use the same syntax that we use for structure members.
book1.title book1.pages book1.author book1.price
initializations
What difference does it make between structure and union? As you know, all members of structure can be accessed at any time. But, only one member of union can be accessed at a time in case of union and other members will contain garbage value. #include <stdio.h> union job { char name[32]; float salary; int worker_no; }u; main() { printf("Enter name:\n"); scanf("%s",&u.name); printf("Enter salary: \n"); scanf("%f",&u.salary); printf("Displaying\nName :%s\n",u.name); printf("Salary: %.1f",u.salary); } Output: Enter name Hillary Enter salary 1234. Displaying Name: f%Bary Salary: 1234.
Example: write a simple program to demonstrate the use of unions. #include<stdio.h> #include<conio.h> void main() { union student { int rollno; char result; }st1.st2; St1.rollno=34; St2.result=’P’; Printf(“\n rollno:%d”,st1.roll_no); Printf(“\n Result:%c”,st2.result”); Printf(“\n\n”); Printf(“\nroll no:%d”,st2.roll_no”); printf(“\nresult:%c”,st1.result”); getch(); } sno Structure Union 1 The keyword struct is used to define a structure
The keyword union is used to define a union.
2 When a variable is associated with a structure, the compiler allocates the memory for each member. The size of structure is greater than or equal to the sum of sizes of its members. The smaller members may end with unused slack bytes.
When a variable is associated with a union,the compiler allocates the memory by considering the size of the largestmemory. So, size of union is equal to the size of largestmember.
3 Each member within a structure is assigned unique storage area of location.
Memory allocated is shared by individual members of union.
4 The address of each member will be in ascending order This indicates that memory for each member will start at different offset values.
The address is same for all the members of a union. This indicates that every member begins at the same offset value.
5 Altering the value of a member will not affect other members of the structure.
Altering the value of any of the member will alter other member values. 6 Individual member can be accessed at a time
Only one member can be accessed at a time.
7 Several members of a structure can initialize at once.
Only the first member of a union can be initialized.
Typedef:
It allows us to introduce synonyms for data types which could have been declared some other way. It is used to give New name to the Structure. New name is used for Creating instances, Passing values to function,declaration etc…
Example : Typedef Sample Program
#include<stdio.h> int main() { typedef int Number; Number num1 = 40,num2 = 20; Number answer;
answer = num1 + num2; printf("Answer : %d",answer); return(0); } Output : Answer : 60
Explanation of Program :
In the above program we have used typedef to create alias name to data type. We have created alias name to ‘int’ data type. We have given new name to integer data type i.e ‘Number’.
Syntax to Use Typedef With Structures :
typedef int XYZ; XYZ age;
enum enum_name { enumeration list } Where, The enum_name specifies the enumeration type name. The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example −
enum Days { sun, mon, tue, wed, thu, fri, sat }; Example The following example demonstrates the use of enum variable −
import std.stdio;
enum Days { sun, mon, tue, wed, thu, fri, sat };
int main(string[] args) { Days day;
day = Days.mon; writefln("Current Day: %d", day); writefln("Friday : %d", Days.fri); return 0; } When the above code is compiled and executed, it produces the following result −
Current Day: 1 Friday : 5
In the above program, we can see how an enumeration can be used. Initially, we create a variable named day of our user defined enumeration Days. Then we set it to mon using the dot operator. We need to use the writefln method to print the value of mon that is been stored. You also need specify the type. It is of the type integer, hence we use %d for printing.
Bit fields:
C permits us to use small bit fields to hold data. We have been using integer field of size 16 bit to store data. The data item requires much less than 16 bits of space, in such case we waste memory space. In this situation we use small bit fields in structures. The bit fields data type is either int or unsigned int. the maximum value that can store in unsigned int filed is :- (2 power n ) – 1 and in int filed is :- 2 power ( n – 1). Here ‘n’ is the bit length. Note : scanf() statement cannot read data into bit fields because scanf() statement, scans on format data into 2 bytes address of the filed. Syntax : struct struct_name { unsigned (or) int identifier1 : bit_length; unsigned (or) int identifier2 : bit_length; ………………………………………….
unsigned (or) int identifierN : bit_length; }; For example, consider the following declaration of date without use of bit fields. #include <stdio.h>
// A simple representation of date struct date { unsigned int d; unsigned int m; unsigned int y; };
int main() { printf("Size of date is %d bytes\n", sizeof(struct date)); struct date dt = {31, 12, 2014}; printf("Date is %d/%d/%d", dt.d, dt.m, dt.y); }
Output:
Size of date is 6 bytes Date is 31/12/
The above representation of ‘date’ takes 6 bytes on a compiler where an unsigned int takes 2 bytes. Since we know that the value of d is always from 1 to 31, value of m is from 1 to 12, we can optimize the space using bit fields. #include <stdio.h>
// A space optimized representation of date struct date { // d has value between 1 and 31, so 5 bits // are sufficient unsigned int d: 5;
// m has value between 1 and 12, so 4 bits // are sufficient unsigned int m: 4;
unsigned int y; };
int main() { printf("Size of date is %d bytes\n", sizeof(struct date)); struct date dt = {31, 12, 2014}; printf("Date is %d/%d/%d", dt.d, dt.m, dt.y); return 0; }
Output: