Unit 3
Unit 3
The pointer can be declared using * (asterisk symbol). Address of p variable is fff4
Value of p variable is 50
INITIALIZATIONS OF POINTER VARIABLE int num = 100;
Address operator (&) is used to initialize a pointer variable. int *ptr; //pointer variable
//pointer initialization
Syntax: data_type * pointer_variable = & variable;
ptr = #
Example:
//printing the value
// Declaration of integer variable printf("value of num = %d\n", *ptr);
int var=10; }
Uses of Pointers
// Initialization of pointer variable
Pointers are used to access memory and manipulate the address.
int *pointer=&var;
Pointer provides power and flexibility to the language.
ACCESSING A VARIABLE THROUGH ITS POINTERS Advantages of Pointers
Access the value of another variable using the pointer variable. 1. Pointers are useful for accessing memory locations.
Steps: 2. Pointers provide an efficient way for accessing the elements of an
Declare a normal variable, assign the value. array structure.
Declare a pointer variable with the same type as the normal 3. Pointers are used for dynamic memory allocation as well as
variable. deallocation.
Initialize the pointer variable with the address of normal variable. 4. Pointers are used to form complex data structures such as linked
Access the value of the variable by using asterisk (*) - it is known as list, graph, tree, etc.
dereference operator (indirection operators). Disadvantages of Pointer
Example Program: 1. Pointers are a little complex to understand.
#include <stdio.h> 2. Pointers can lead to various errors such as segmentation faults or
void main() can access a memory location which is not required at all.
{ 3. If an incorrect value is provided to a pointer, it may cause memory
//normal variable corruption.
4. Pointers are also responsible for memory leakage. // Program showing pointer expressions during Arithmetic Operations
5. Pointers are comparatively slower than that of the variables. #include <stdio.h>
6. Programmers find it very difficult to work with the pointers; void main()
therefore it is programmer's responsibility to manipulate a pointer {
carefully. // Integer variables
POINTER EXPRESSION int a = 20, b = 10;
Pointers are valid operands in arithmetic expressions, assignment // Variables for storing arithmetic // operations solution
expressions and comparison expressions. int add, sub;
// Pointer variables for variables a and b
int *ptr_a, *ptr_b;
// Initialization of pointers
ptr_a = &a;
ptr_b = &b;
// Performing arithmetic Operations on pointers
add = *ptr_a + *ptr_b;
sub = *ptr_a - *ptr_b;
To perform arithmetic operations to pointer variables using // Printing values
arithmetic operators, we can add an integer or subtract an integer printf("Addition = %d\n", add);
using a pointer pointing to that integer variable. printf("Subtraction = %d\n", sub);
Examples: }
*ptr1 + *ptr2 Output:
*ptr1 * *ptr2 Addition = 30
*ptr1 + *ptr2 - *ptr3 Subtraction = 10
Example Program:
CHAIN OF POINTERS Pointers and Arrays
A pointer is used to point to a memory location of a variable. Variable declared as an array of some type acts as a pointer to that
A pointer stores the address of a variable. type. When used by itself, it points to the first element of the array.
Similarly, a chain of pointers is when there are multiple levels of A pointer can be indexed like an array name.
pointers.
The level of the pointer depends on how many asterisks the pointer
variable is preceded with at the time of declaration.
Syntax:
datatype *pointer;
datatype **pointer;
... };
void main()
};
{
Example:
struct Person person1, person2, p[20];
}
How to Initialize Structure Members?
Structure members cannot be initialized like other variables inside
the structure definition.
Because when a structure is defined, no memory is allocated to the
structure’s data members at this point. Memory is only allocated
when a structure variable is declared.
Example:
struct rectangle
struct rectangle
{
{
Create struct Variables // structure definition
// structure definition
When a struct type is declared, no storage or memory is allocated. int length;
int length = 10; // COMPILER ERROR:
To allocate memory of a given structure type and work with it, we int breadth;
cannot
};
need to create variables. initialize members here.
void main()
Example int breadth = 6; // COMPILER ERROR:
{
struct Person cannot
struct rectangle my_rect; // structure
{ initialize members here.
variables;
char name[50]; };
my_rect.length = 10;
int citNo; my_rect.breadth = 6;
}
Access Members of a Structure printf("Roll No.: %d\n", student1.rollno);
There are two types of operators used for accessing members of a printf("College: %s", student1.college);
structure. }
. Member operator Output
-> Structure pointer operator Name : Hariharasudhan.S
Example Program Roll No : 2001
#include <stdio.h> College : SRM Trichy Arts and Science College
#include <string.h> Array of Structures
// create struct with person1 variable An array of structures acts similar to a normal array.
struct student The name of the structure followed by the dot operator (.) and the
{ name of the array has to be mentioned to access an array element.
char name[50]; To store the details of 100 students name, class, and roll number in
int rollno; your database, we use array of structures.
char college[50]; Example:
#include <stdio.h>
} student1;
// structure definition
void main() struct Student
{
{
// data members
// assign value to name of person1 char name[10];
int marks;
strcpy(student1.name, "Hariharasudhan.S");
};
// assign values to other person1 variables // declare an array of the structure Student.
struct Student stu[3];
person1.rollno = 2001;
int i, j;
person1. college = “SRM Trichy Arts and Science College”; // function to read the values from the user and print them.
void print()
// print struct variables
{
printf("Name: %s\n", student1.name); // read input from the user.
for (i = 0; i < 3; i++) Student Name : S. Hariharasudhan
{ Enter marks : 99
printf("\nEnter the record of Student %d\n", i + 1); Student Name : M.Prabhu
printf("\nStudent name: "); Enter marks : 98
scanf("%s", stu[i].name); Keyword typedef
printf("Enter Marks: ");
Use the typedef keyword to create an alias name for data types.
scanf("%d", &stu[i].marks);
} It is commonly used with structures to simplify the syntax of
// print the details of each student.
declaring variables.
printf("\nDisplaying Student record\n"); Example 1: (without using typedef)
for (i = 0; i < 3; i++)
struct Distance
{
printf("\nStudent name is %s", stu[i].name); {
printf("\nMarks is %d", stu[i].marks);
int feet;
}
} float inch;
void main()
};
{
// function call void main()
print();
{
}
Output: struct Distance d1, d2;
Enter the record of Student 1
}
Student Name : S. MONICA
Enter marks : 98 Example 2 : (Using typedef keyword)
Enter the record of Student 2
typedef struct Distance
Student Name : S. Hariharasudhan
Enter marks : 99 {
Enter the record of Student 3
int feet;
Student Name : M.Prabhu
Enter marks : 98 float inch;
Displaying Student record
} distances;
Student Name : S. MONICA
Enter marks : 98 void main()
{ void printBook( struct Books *book );
void main( )
distances d1, d2;
{
} struct Books Book1; // Declare Book1 of type Book
strcpy( Book1.title, "C Programming"); // book 1
POINTERS AND STRUCTURES
specification
Define pointers to structures in the same way as we define strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
pointer to any other variable.
Book1.book_id = 6495407; // print Book1 info by
struct Books *struct_pointer; passing address of Book1
}
Now, we can store the address of a structure variable in the
void printBook( struct Books *book )
above defined pointer variable. {
printf( "Book title : %s\n", book->title);
To find the address of a structure variable, place the ‘&’;
printf( "Book author : %s\n", book->author);
operator before the structure’s name as printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
follows
}
struct_pointer = &Book1; Output:
Book title : C Programming Book
To access the members of a structure using a
Author : Nuha Ali
pointer to that structure, we must use the → operator as Book subject : C Programming Tutorial
Book book_id : 6495407
follows −
UNION
struct_pointer->title;
A union is a special data type available in C
Example Program
It allows storing different data types in the same memory location.
#include <stdio.h>
#include <string.h> Unions provide an efficient way of using the same memory location
struct Books
for multiple-purpose.
{
char title[50]; Defining a Union
char author[50];
Union keyword is used to define union structure.
char subject[100];
int book_id; The union statement defines a new data type with more than one
};
member for our program. printf("\n b = %d", var.b);
Syntax: }
union [union tag] Differences between Structure and Union
{ Structure Union
member definition;
1. use a struct keyword to define 1. use a union keyword to
member definition; a structure. define a union.
... 2. Every member within structure 2. A memory location is shared
is assigned a unique memory by all the data members.
member definition; location.
} [one or more union variables]; 3. Changing the value of one data 3. Changing the value of one
member will not affect other data member will change the
Accessing Union Members data members in structure value of other data members
To access any member of a union, use the member access operator in union.
4. It enables you to initialize 4. It enables you to initialize
(.). several members at once. only the first member of
The member access operator is coded as a period between the union.
5. It is mainly used for storing 5. It is mainly used for storing
union variable name and the union member that we wish to access. various data types. one of the many data types
Example: that are available.
6. It supports flexible array. 6. It does not support a flexible
union abc array.
{ 7. You can retrieve any member 7. You can access one member
at a time. at a time in the union.
int a; 8. It occupies space for each and 8. It occupies space for a
char b; every member written in inner member having the highest
parameters. size written in inner
}var; parameters.
void main() 9. The total size of the structure is 9. The total size of the union is
the sum of the size of every the size of the largest data
{ data member. member.
var.a = 66;
printf("\n a = %d", var.a);