0% found this document useful (0 votes)
33 views9 pages

C Unit-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views9 pages

C Unit-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

UNIT-IV:

POINTERS, STRUCTURES AND UNIONS

Pointers:

 Features of pointers
 Declaration of Pointers-
 arithmetic operations with pointers.

Structures:

 Features of Structures –
 Declaring and initialization of Structures –
 Structure within Structure-
 Array of Structures-
 Enumerated data type-

Unions-

 Definition and advantages of Unions 2021


 comparison between Structure & Unions.2021
What is a pointer?
➔ A pointer is a variable that stores the memory address of another variable as its value.
➔ A pointer is a derived data type in C. It is built from one of the fundamental data types
available in C.
➔ Pointers contain memory addresses as their values. Since these memory addresses are
the locations in the computer memory where program instructions and data are stored,
pointers can be used to access and manipulate data stored in the memory.

Features of Pointers:
1. Pointers save memory space.
2. Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
4. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional
arrays.
5. An array, of any type can be accessed with the help of pointers, without considering its
subscript range.
6. Pointers are used for file handling.
7. Pointers are used to allocate memory dynamically.
8. In C++, a pointer declared to a base class could access the object of a derived class.
However, a pointer to a derived class cannot access the object of a base class.
Advantages of Pointers
Pointers are used frequently in C, as they offer a number of benefits to the programmers.
They include the following:

1. Pointers are more efficient in handling arrays and data tables.


2. Pointers can be used to return multiple values from a function via function arguments.
3. Pointers allow passing a function as argument to other functions.
4. The use of pointer arrays to character strings results in saving of data storage space in
memory.
5. Pointers allow C to support dynamic memory management.
6. Pointers provide an efficient way for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
7. Pointers increase the execution speed and thus reduce the program execution time.
Declaration of Pointers-
➔ Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing.
➔ void type pointer works with all data types, but is not often used.
➔ Here are a few examples:

int *ip // pointer to integer variable


float *fp; // pointer to float variable
double *dp; // pointer to double variable
char *cp; // pointer to char variable
Initialization of C Pointer variable
➔ Pointer Initialization is the process of assigning address of a variable to a pointer variable.
Pointer variable can only contain address of a variable of the same data type.
➔ In C language address operator & is used to determine the address of a variable.
➔ The & (immediately preceding a variable name) returns the address of the variable
associated with it.

#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}

Arithmetic operations with pointers.


➔ Sometimes we need to perform arithmetic operations on pointers.
➔ But before using arithmetic operators with pointers we need to understand that we can not
use each arithmetic operators with pointers.
➔ Pointer arithmetic is slightly different from arithmetic we normally use in our daily life.
➔ We also need to remember that we cannot use the multiplication or division operator with
the pointer. Below are some arithmetic operations with pointers.

Indirection (*) This operator is used to get the value from the pointed
address.
Reference operator (&) This operator is used to get the address of the variable
or pointer.
Assignment (=) You can assign the value to the pointer or value to the
address which is pointed by the pointer.

Addition (+) You can add integer value to the pointer to point the
different memory locations.

Subtraction (-) You can subtract the integer value from the pointer to
point the different memory locations.

comparison (==, !=, <, >, <=, This operation is valid only between two pointers that
and >=) point to the same array.

Incrementing (++) You can use increment operators (pre and post) with
the pointer.
Decrementing (–) You can use decrement operators (pre and post) with
the pointer.
➔ When we increment or decrement the pointer then pointer increase or decrease a block of
memory (block of memory depends on pointer data type).

Structures - Features of Structures –


➔ A structure is a collection of heterogeneous data elements referred by the same name.
➔ Structures are mostly used for maintaining records like mark sheets with student details like
name, ID number, and marks stored under the same name.

Declaring and initialization of Structures:


Unlike arrays, structures must be first defined first for their later use.

The syntax for defining a structure is as shown below:


struct structure_name/tagname
{
datatype var1;
datatype var2;
----
----
};

 The keyword struct declares a structure.

 The structurename / tagname represents the name of the structure.

 The structure definition is always terminated with a semicolon.

Ex:

struct student

char name[20];

char rollno[15];

int age;

char grade;

};

 In the above example, student is the name of the structure.


 The members of the student structure are: name, rollno, age and grade.
 A structure itself does not occupy any memory in the RAM.
 Memory is allocated only when we create variables using the structure.
Declaring Structure Variables

 After defining a structure, we can create variables of that type.


 A structure variable declaration is similar to the declaration of variables of any other data
types.
syntax: struct structure_name var1, var2, …., varN;

ex: struct student student1, student2, student3;

 We can also combine the structure definition and the declaration of structure variables into
a single line as shown below:

struct student
{
char name[20];
char rollno[15];
int age;
char grade;
} student1, student2, student3;

Structure Initialization

 Like any other data type, a structure variable can be initialized at compile time.
 An example of compile time initialization of the student structure is shown below:

struct student
{
char name[20];
char rollno[15];
int age;
char grade;
};
struct student student1 = {“Abhishek”, ”101”, 20, ’A’};
struct student student2 = {“Sri kanth”, ”102”, 21, ’B’};

Structures within Structure


 In C, structures can be nested.
 A structure can be defined within in another structure.
 The members of the inner structure can be accessed using the variable of the outer
structure as shown below:

struct student
{
struct
{
char fname[20];
char mname[20];
char lname[20];
}name;
char grade;
};
struct student s1;
strcpy(s1.name.fname, “Abhishek”);
 In the above example, student is the outer structure and the inner structure name consists
of three members: fname, mname and lname.

Arrays of Structures
 We use structures to describe the format of a number of related variables.
 For example, we want to store details of 100 textbooks it will become difficult to declare
and maintain 100 variables and store the data.
 Instead, we can declare and array of structure variables as shown below:

struct textbook
{
char name[40];
char author[20];
int pages;
}
struct textbook book[10];
In the above example, we are declaring an array book with 10 elements of the type textbook which
is a structure.

Enumerated data type:


 Enumeration or Enum in C is a special kind of data type defined by the user.
 It consists of constant integrals or integers that are given names by a user.
 The use of enum in C to name the integer values makes the entire program easy to learn,
understand, and maintain by the same or even different programmer.
 An enum is defined by using the ‘enum’ keyword in C, and the use of a comma separates the
constants within.
 The basic syntax of defining an enum is:

enum enum_name{int_const1, int_const2, int_const3, …. int_constN};

 In the above syntax, the default value of int_const1 is 0, int_const2 is 1, int_const3 is 2, and
so on.
 However, we can also change these default values while declaring the enum.
 Below is an example of an enum named cars and how you can change the default values.

enum cars {BMW, Ferrari, Jeep, Mercedes-Benz};

Here, the default values for the constants are:

 BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3. However, to change the default values,
we can define the enum as follows:

enum cars
{
BMW=3,
Ferrari=5,
Jeep=0,
Mercedes-Benz=1
};
Enumerated Type Declaration to Create a Variable
 Similar to pre-defined data types like int and char, you can also declare a variable for enum
and other user-defined data types.

Example 1: Printing the Values of Weekdays

#include <stdio.h>

enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main()
{
// printing the values of weekdays
for(int i=Sunday; i<=Saturday; i++)
{
printf("%d, ",i);
}
return 0;
}

Unions:
 Unions have the same syntax as that of a structure since both of them are similar.

 However, there is a major difference between them in terms of memory allocation.

 A structure is allocated memory for all the members of the structure whereas a union is
allocated memory only for largest member of the union.

 This implies that, although a union may contain many members of different types, it can
handle only one member at a time.

 Like structure, a union can be declared using the union keyword as shown below:

union student
{
char name[20];
char grade;
};
union student s1,s2;

 In the above code student is the name of the union.

 Also s1 and s2 are union variables.


 Memory is allocated only for name member of the union.

 So, the limitation on unions is: only one member can be used at a time.

 Unions can be used in all places where a structure is allowed.

 Below is a C program to demonstrate a union:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
union student
{
char name[20];
char grade;
int marks;
};
union student s1;

strcpy(s1.name,"Abhishek");
s1.grade = 'A';
s1.marks = 98;
printf("Name is: %s \n",s1.name);
printf("Grade is: %c \n",s1.grade);
printf("Marks are: %d",s1.marks);
return 0;
}

comparison between Structure & Unions:


 Structure and union both are user-defined data types.

Struct Union
1 The struct keyword is used to define a The union keyword is used to define union.
structure.
2 When the variables are declared in a structure, When the variable is declared in the union,
the compiler allocates memory to each the compiler allocates memory to the largest
variables member. The size of a structure is size variable member. The size of a union is
equal or greater to the sum of the sizes of each equal to the size of its largest data member
data member. size.
3 Each variable member occupied a unique Variables members share the memory space
memory space. of the largest size variable.
4 Changing the value of a member will not affect Changing the value of one member will also
other variables members. affect other variables members.
5 Each variable member will be assessed at a Only one variable member will be assessed
time. at a time.
6 We can initialize multiple variables of a In union, only the first data member can be
structure at a time. initialized.
7 All variable members store some value at any
Exactly only one data member stores a value
point in the program. at any particular instance in the program.
8 The structure allows initializing multiple Union allows initializing only one variable
variable members at once. member at once.
9 It is used to store different data type values.
It is used for storing one at a time from
different data type values.
10 It allows accessing and retrieving any data It allows accessing and retrieving any one
member at a time. data member at a time.

You might also like