Unit - 5 - GVK

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Vallurupalli Nageswara Rao Vignana Jyothi Institute of

Engineering &Technology

Department of ECE

SUBJECT: C PROGRAMMING
Subject Code:

Topic Name: Structures, Unions & Pointers


I year, sec:

Vijaya Kumar G
Assistant Professor, ECE

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 1


Agenda
▪ Structures & Unions: Defining structures and array of structures,
Unions, Typedef, Bitfields

▪ Pointers: Idea of pointers, defining pointers, Use of pointers in self


referential structures, Notation of linked list(no implementation),
Dynamic memory allocation

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 2


Department of ECE, VNRVJIET, Hyderabad March 29, 2022 3
Structures
Array vs Structure
• Recall that an array is a collection of data items, all having the same data
type and accessed using a common name and an integer index into the
collection.

• A struct is also a collection of data items, except with a struct the data
items can have different data types, and the individual fields within the
struct are accessed by name instead of an integer index.

▪ It is a mechanism for packing data of different types.

• It is a convenient tool for handling a group of logically related data items


possibly of different types.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 5


Structures in C :1`

• Structure provides a way to store multiple variables of similar or different


types under one umbrella.

• This makes information more packaged and program more modular as


different variables referring to different values can be accessed through a
single structure object.

• A user-defined DATA TYPE which holds more than one elements of different
data types.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 6


Structure Definition
Syntax: Example:
struct structure_name struct student
{ {
data_type member1; int rollno;
char name[20];
data_type member2;
};
....
data_type memeberN; struct Books {
}; char title[50];
char author[50];
int book_id;
};

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 7


Structures

➢ struct is the keyword

➢ student is the name of the structure

➢ rollno, name are the members or fields of the structure

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 8


STRUCTURE
Accessing Structure Members
MEMORY ALLOCATION
Image shows the memory allocation of the structure employee
that is defined in the above example.
Accessing Members

➢ There are two ways to access structure members:


Dot operator(.) , Indirectional operator(*) , Selector operator(->)
▪ Here (*) and (->) operators are used when we use pointers to
structure

Example: variable Example: pointer


Std1.rollno=123456; Std1->rollno=123456;
Std1.name=“Raju”; Std1->name=“Raju”;

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 10


Structure Variable Declaration
➢ Using structure variable, we can access the members of the
structure. We can declare them in two ways

1) declaring a variable at the 2) Inside main():

time of defining the struct student std1, std2;


structure:
struct student
{
int rollno;
char name[20];
}std1,std2;

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 11


1) struct Test void main()
{
{ struct Test r1;
r1.a = 20;
int a, b;
}; }

2) struct Test void main()


{
{ r1.a = 20;
int a, b;
}
}r1 ;

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 12


Which approach is good

If number of variables are not fixed, use with in main approach.


It provides you the flexibility to declare the structure variable
many times.
If no. of variables are fixed, use struct declaration approach. It
saves your code to declare a variable in main() function.
Accessing Members in program
The link between a member and a structure variable is established using
.
member operator ‘ ’ Which is also called as dot operator or period operator .

#include<stdio.h>
struct Test{
int a, b;
};
void main() {
struct Test r1 ;
r1.a = 20;
r1.b = 50;
printf (“a = %d, b = %d", r1.a, r1.b);
}
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 14
Initialization
Structure members can also be initialized using curly braces ‘{}’
struct Test{
int a, b;
};
void main() {
struct Test r1 = {5, 6};
//struct Test r1 = {.b =6, .a = 5};
printf (“a = %d, b = %d", r1.a, r1.b);
}
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 15
Initialization and accessing of structures
Rules for Initialization of structure
i) We cannot initialize individual members inside structure template.
ii) The order of values enclosed in braces must match with order of
members in structure definition.
iii) partial initialization is permitted ,we can initialize only the 1st few
and leave the remaining blank.
NOTE: non-initialized members should be only at the end of the list
iv)The non-initialized members will be assigned with default values as follows
0(zero) for integers and floating point number ‘\0’ for characters and strings
We can initialize the structure at compile time or at runtime
Initialization can be done in the following ways
1.struct book
{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};

2.struct book
{
int pages;
char author[30];
float price;
};
struct book b = {100, “balu”, 325.75};
3.using member operator
struct book
{
int pages;
char author[30];
float price;
};
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;
4.using scanf ( )
struct book
{
int pages;
char author[30];
float price;
};
struct book b;
scanf (“%d”, &b.pages);
scanf (“%s”, b.author);
scanf (“%f”, &b. price);
In the above examples first three ways are compile time initialization and the fourth way
i.e using scanf is runtime initialization.
Complex Structures:

Complex structures deals with concepts such as

i) Array of structures
ii) Arrays with in Structure
iii) Nested structure
iv) Pointer to structure

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 20


Array of Structures
➢ Array can store the multiple Structures in it i.e., used to store
information about multiple entities

Example: Void main()


{
struct Test // struct Test B[5];
{ B[0].a = 10;
B[0].b = 20;
int a, b;
}B[5]; printf("%d %d", B[0].a, B[0].b);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 21


Array of Structures
Example: void main()
{
#include<stdio.h> B[0].a=10;
struct student B[0].b='C';
B[1].a=30;
{ B[1].b=40;
int a; printf("%d\t%c",B[0].a,B[0].b);
printf("\n%d\t%d",B[1].a,B[1].b);
char b; }
}B[5];

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 22


Array of Structures program
#include<stdio.h> for(i=0;i<5;i++)
#include <string.h> {
struct student{ printf("\nEnter Rollno:");
int rollno; scanf("%d",&std[i].rollno);
char name[10]; printf("\nEnter Name:");
}; scanf("%s",&std[i].name);
}
void main(){ printf("\nStudent Information List:");
int i; for(i=0;i<5;i++){
struct student std[5]; printf("\nRollno:%d, Name:%s",std[i].roll
printf("Enter Records of 5 no,std[i].name);
students"); }
}
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 23
Program: For accepting and printing details of 10 students
struct student {
int sno;
char sname[30];
float marks; };
main ( ){
struct student s[5];
int i;
for (i=0; i<5; i++)
{
printf(“enter details of students %d”, i+1);
scanf (“%d %s %f ”, & s[i]. sno, s[i]. sname, &s[ i].marks);
}
for (i=0; i<5; i++) {
printf (“the details of student %d are”, i+1);
printf (“Number = %d”, s[i]. sno);
printf (“name = %s”, s[i]. sname);
printf (“marks =%s”, s[i]. marks);
}
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 24


Arrays within structures :

Arrays can be declared / used with in structure.


ie. structure may contain one or more arrays as member.
#include<stdio.h>
struct student
{
char name[25];
int midmarks[3];
};
void main(){
int i;
struct student s={“Madhu",{25,24,25}};
printf("name of student is :%s",s.name);
for(i=0;i<3;i++)
printf("%d mid marks are:%d",i++,s.midmarks[i]);
}
Nested structures :

Structure within structure (or) Nested structures


Creating a structure inside another structure is called nested structure.
This structure defines sno, name and 3 midmarks. All the items
related to marks can be grouped together and declared under a sub –
structure as shown below:
struct student
{
struct student int sno;
{ char name[30];
int sno; struct marks
char name[30]; {
int mid1; int mid1;
int mid2; int mid2;
int mid3; int mid3;
}s; }m;
}s;
Accessing member :
The inner most member in a nested structure can be accessed by
chaining all the concerned structure variables (from outer most to
inner most) with the member using dot operator
Outer structures members can be accessed by using
outer_structure_variable.member i.e. s.sno and s.name
Inner structures members can be accessed by using
outer_structure_variable. inner_structure_variale .member
i.e. s.m.mid1 ,s.m.mid2 and s.m.mid3
Program void main ( )
struct student {
{
clrscr ( );
int sno;
char name[30];
printf(“enter sno, name”);
struct marks scanf (“%d%s”, &s.sno, s.name);
{ printf (“enter mid1 ,mid2 and mid3 marks”);
int mid1; scanf
int mid2; ("%d%d%d",&s.m.mid1,&s.m.mid2,&s.m.mid3);
int mid3; printf(“student details are”)
}m; printf (“ serial number = %d”, s.sno);
}s; printf (“name = %s”, s.name);
printf(“marks details:");
printf(“mid 1 marks:%d",s.m.mid1);
Note: printf(“mid 2 marks:%d",s.m.mid2);
Inner structure can printf(“mid 3 marks:%d",s.m.mid3);
have more than one
getch ( )
variable. The variables
are separated from
return;
another variable with }
comma.
Nested Structures program
#include<stdio.h> void main ()
struct address {
{ struct employee emp;
char city[20]; printf("Enter emp info\n");
int pin; scanf("%s %s %d
char phone[14]; %s",emp.name,emp.add.city,
}; &emp.add.pin, &emp.add.phone);
struct employee printf("employee Details.\n");
{ printf("name: %s\nCity: %s\nPincode:
char name[20]; %d\nPhone:
struct address add; %s",emp.name,emp.add.city,emp.add.pi
}; n,emp.add.phone);
}
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 31
STRUCTURES AND FUNCTIONS

Any user-defined function can be performed on structure values by passing structure


values as arguments to the function. This can be done in three ways:-

(i) Each member of a student can be passed individually as function arguments but
this method becomes difficult when the structure contains more number of elements.

(ii) A copy of entire structure can be passed from calling function to the called
function. Here, the changes made in called function do not reflect in the calling function.

(iii) The address location of the structure can be passed to the function. Here the
changes made in the called function are reflected in the calling function.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 32


#include<stdio.h>
struct employee
{
int empid;
float salary;
};
void display(int,float);
void main()
{
struct employee e1={105,5000.5};
display(e1.empid,e1.salary);
}
void display(int a,float b)
{
printf("employee_id=%d\nemployee_salary=%f",a,b);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 33


#include<stdio.h>
struct employee
{
int empid;
float salary;
};
void display(struct employee);
void main()
{
struct employee e1={105,5000.5};
display(e1);
}
void display(struct employee d)
{
printf("empid=%d\nsalary=%f",d.empid,d.salary);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 34


#include<stdio.h>
struct book
{
char name[10];
char author[10];
int pages;
};
void display(struct book *);
void main()
{
struct book b1={"c&ds","dennis",250};
display(&b1);
}
void display(struct book *b2)
{
printf("name=%s\nauthor=%s\npages=%d",b2->name,b2->author,b2->pages);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 35


Pointers to Structures
#include<stdio.h>
struct Test *r2 = &r1;
struct Test
{ printf("%d %d", r2->a, r2->b);
int a, b; return 0;
}; }

int main()
{
struct Test r1 = {10, 20};

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 36


global
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure

void structure_demo();

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 37


Typedef
➢ typedef is a keyword used in C

➢ Used to provide some meaningful names to the already existing


data types in C

➢ used to redefine the name of an already existing data types


➢ typedef <existing_name> <new_name>

Example:

typedef unsigned int UC;

UC a, b;

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 38


Typedef in structures
struct student typedef struct student
{ {
char name[20]; char name[20];
int age; int age;
};
} stud;
typedef struct student stud;
stud s1,s2;
stud s1, s2;

In the above statement, we have typedef keyword reduces the


declared the variable stud of type length of the code and
struct student. Now, we can use complexity of data types. It also
the stud variable in a program to helps in understanding the
create the variables of type struct program.
student.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 39


#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 40


#include <stdio.h>
#include <string.h>

typedef struct Books_library {


char title[50];
char author[50];
char subject[100];
int book_id;
} Book_details;

int main( ) {
Book_details book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;

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; }

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 41


typedef vs #define
#define is a C-directive which is also used to define the aliases for
various data types similar to typedef but with the following differences −

• 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.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 42


BITFIELDS:

▪ A bitfield is a set of adjacent bits whose size can be from 1 to 16 bits.


Bitfield provides exact amount of bits required to store values i.e., for
example when an integer is declared, 2 bytes are allocated to store an
integer which we may or may not completely utilize.

Therefore, to avoid wastage of memory, we mention the exact bit size. The
name and size of bit fields are defined using a structure.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 43


Here, the datatype can be either int or
▪ Syntax:-
unsigned int or signed int.
Struct tagname Bit length specifies the number of bits
{ used under that name.
Here the colon(:) tells the compiler that
datatype member1:bit length;
bitfields are used in the structure.
datatype member2:bit length;
In a bitfield of lenght1 we can store the
:: values 0,1.
datatype member n:bit length; In a bitfield of lenght2 we can store the
values 0,1,2,3.
};
Similarly, in a bit field of lenght1 we
can store the values 0,to 2n-1.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 44


Note:

1. We cannot take address of a bitfield, hence pointers cannot be


used to access bitfields.
2. scanf( ) statement cannot be used to read values in bitfields.
3. bitfields cannot be arrayed.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 45


#include <stdio.h>
#include <string.h>

/* define simple structure */


struct {
int member1;
int member2;
} status1;

/* define a structure with bit fields */


struct {
int member1 : 1;
int member2 : 1;
} status2;

int main( ) {
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
printf( "Memory size occupied by status2 : %d\n", sizeof(status2));
return 0;
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 46


▪ The above structure requires 4 bytes of memory space for status
variable, but only 2 bits will be used to store the values.

▪ If you will use up to 32 variables each one with a width of 1 bit, then
also the status structure will use 4 bytes. However as soon as you
have 33 variables, it will allocate the next slot of the memory and it will
start using 8 bytes.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 47


Unions

➢ union is also an user-defined data type

➢ only one member of the union can occupy the memory at once

➢ Similar to structures unions are also allow to store different data


types

➢ size of the union in any instance is equal to the size of its largest
element

➢ In union, all members share the same memory location

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 48


Unions Definition
Syntax Example

union name { union Test


member definition; {
member definition; int i;
... float f;
member definition; char str[8];
} [one or more union variables]; } r1;

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 49


Unions Definition
#include <stdio.h>
union Test {
int i;
float f;
char str[8];
};
void main( ) {

union Test t1;

printf( "Memory occupied by Test is : %d\n", sizeof(t1));


}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 50


Structures vs Unions
Structures Unions

struct Test1 { union Test {


int i; int i;
float f; float f;
char str[8]; char str[8];
}R1; }R2;
R1→ ( 16 Bytes of memory) R2→ ( 8 Bytes of memory)
(memory required by its largest
element is allocated)

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 51


Memory in unions
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union item. The union contains three
members, each with a different data type. However, we can use only one of
them at a time. This is due to the fact that only one location is allocated for a
union variable, irrespective of its size.

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 52


Example program
#include <stdio.h>
union Test {
int a, b; t1.a = 5; // t.b also gets value 5
}; printf("After making a = 5:\n a = %d, b = %d\n",
void main() t.a, t.b);
{ t.b = 6; // t.a is also updated to 6
union Test t1; printf("After making b = 6:\n a = %d, b = %d\n",
t.a, t.b);
}

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 53


Example program
#include <stdio.h>
#include <string.h>
union student strcpy(std1.name, "Raju");
{ int id; printf( “student 1 id : %d\n", std1.id);
char name[30]; printf( “student 1 name : %s\n", std1.name);
}std1; }
void main( )
{ Output:
std1.id=544; student 1 id : 2769506437
student 1 name : Raju
Note: value of id is corrupted because the
final value assigned to the variable has
occupied the memory location
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 54
Union usage program
#include <stdio.h>
#include <string.h> printf( “student 1 id : %d\n", std1.id);
union student strcpy(std1.name, "Raju");
{ int id; printf( “student 1 name : %s\n", std1.name);
char name[30]; }
}std1;
void main( )
{ Output:
std1.id=544; student 1 id : 544
student 1 name : Raju

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 55


Department of ECE, VNRVJIET, Hyderabad March 29, 2022 56
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 57
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 58
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 59
Department of ECE, VNRVJIET, Hyderabad March 29, 2022 60
THANK YOU

Department of ECE, VNRVJIET, Hyderabad March 29, 2022 61

You might also like