SlideShare a Scribd company logo
CLASS:FYBSC(CS)-E
SUBJECT: “ADVANCE C PROGRAMMING”
SEM-II
SYLLABUS: ”Advance C Programming” SEM-II
CH.1 POINTERS
CH.2 STRINGS
CH.3 STRUCTURES AND UNION
CH.4 FILE HANDLING
CH.5 PREPROCESSOR
Chapter 1 :Pointers
• Chapter 1 :Pointers
• 1.1. Introduction to Pointers.
• 1.2. Declaration, definition, initialization, dereferencing.
• 1.3. Pointer arithmetic.
• 1.4. Relationship between Arrays & Pointers- Pointer to array, Array of
pointers.
• 1.5. Multiple indirection (pointer to pointer).
• 1.6. Functions and pointers- Passing pointer to function, Returning pointer
from function, Function pointer.
• 1.7. Dynamic memory management- Allocation(malloc(),calloc()),
Resizing(realloc()), Releasing(free()).,
• 1.8. Memory leak, dangling pointers.
• 1.9. Types of pointers.
CH.1 POINTERS
INTRODUCTION:
• Pointers in C are easy and fun to learn.
• Some C programming tasks are performed more easily with
pointers, and other tasks, such as dynamic memory allocation,
cannot be performed without using pointers.
• So it becomes necessary to learn pointers to become a perfect C
programmer.
INTRODUCTION:
continue…
• 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.
• As you know, every variable is a memory location and every
memory location has its address defined which can be
accessed using ampersand (&) operator, which denotes an
address in memory.
Example:
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %xn", &var1 );
printf("Address of var2 variable: %xn", &var2 );
return 0; }
Definition,Declaration,Initialization,
Dereferencing of pointers.
• Definition of pointers:
• A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location. Like any
variable or constant, you must declare a pointer before using it
to store any variable address.
• Other Definitions:
1.Pointer is a variable that holds memory address.
2.Pointer is a variable which holds the address of another
variable. It contains the memory location of the variable instead
of its content.
How to Use Pointers
• There are a few important operations, which we will do with the
help of pointers very frequently.
• (a) We define a pointer variable,
• (b) assign the address of a variable to a pointer and
• (c) finally access the value at the address available in the
pointer variable.
• This is done by using unary operator * that returns the value of
the variable located at the address specified by its operand.
Declaration of Pointer
• The pointer in c language can be declared using *
(asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.
1.int *a;//pointer to int
2.char *c;
3.float *d//pointer to float
Example 1:
#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 address of the number therefore printing p gives the address of number
.
printf("Value of p variable is %d n",*p);
//Here we will get the value stored at the address contained by p.
return 0;
}
Initialization of Pointers
• When we declare a pointer variable it contains garbage value.
i.e. It may be pointing anywhere in the memory. So we should always
assign an address before using it in the program.
• Pointer initialization is the process of assigning address of a variable
to a pointer variable. Pointer variable can only contain address of the
same data type.
• Syntax:
• <pointer declaration>
• Pointer_name =&variable<address of avariable>
Initialization of Pointers-Example
EX1:
Int n,*iptr;
iPtr=&n;
Ex2:
Int a=30,*ptr;
Ptr=&a;
We can also initialize the pointer at the time of declaration.
Ex3:
Int roll=102,*ptr=&roll;
Float sal=5000.00,*fptr=&sal;
sizeof() operator in C
• The sizeof() operator is commonly used in C.
• It determines the size of the expression or the data
type specified in the number of char-sized storage
units.
• The sizeof() operator contains a single operand which
can be either an expression or a data typecast where
the cast is data type enclosed within parenthesis.
• The data type cannot only be primitive data types such
as integer or floating data types, but it can also be
pointer data types and compound data types such as
unions and structs.
Example:
1. sizeof(datatype)
2. Sizeof(pointer variable)
#include <stdio.h>int main()
{ char a='A'; char *ptr; ptr=&a; printf("n sizeof(ptr)=%d",
sizeof(ptr)); printf("nsizeof(a)=%d",sizeof(a));
printf("nsizeof(*ptr)=%d",sizeof(*ptr)); return 0;}
Use of sizeof() operator
• we dynamically allocate the array space by
using sizeof() operator:
• Example:
• int *ptr=malloc(10*sizeof(int));
• We use malloc() function to allocate the memory and
returns the pointer which is pointing to this allocated
memory. The memory space is equal to the number of
bytes occupied by the int data type and multiplied by
10.
Dereferencing of Pointers:
• When indirection operator (*) is used with the pointer
variable, then it is known as dereferencing a
pointer.
• When we dereference a pointer, then the value of the
variable pointed by this pointer will be returned.
Differencing Pointer or Subtraction of pointer
from another pointer:
• Pointer variable can be subtracted from another pointer variable only
if they point to the elements of the same array.
• Syntax:
• Ptr_variable2-ptr_variable1
Why we use dereferencing pointer?
• Dereference a pointer is used because of the
following reasons:
• It can be used to access or manipulate the data stored
at the memory location, which is pointed by the pointer.
• Any operation applied to the dereferenced pointer will
directly affect the value of the variable that it points to.
Example: Dereferencing of pointer
#include <stdio.h>
int main()
{
int x=9;
int *ptr;
ptr=&x;
*ptr=8; //*ptr will update the value of x
printf("value of x is : %d", x);
return 0;
}
Example 2:
#include <stdio.h>
int main()
{
int a=90;
int *ptr1,*ptr2;
ptr1=&a;
ptr2=&a;
*ptr1=7;
*ptr2=6;
printf("The value of a is : %d",a);
return 0;
}
Pointer Arithmetic
• 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
• If we increment a pointer by 1, the pointer will start
pointing to the immediate next location.
• This is somewhat different from the general arithmetic
since the value of the pointer will get increased by the
size of the data type.
• We can traverse an array by using the increment
operation on a pointer which will keep pointing to every
element of the array, perform some operation on that,
and update itself in a loop.
The Rule to increment the pointer is
given below:
Syntax:
new_address= current_address + i * size_of(data type)
• Where i is the number by which the pointer get
increased.
• pe to which the pointer is pointing.
Example: Incrementing a pointer Variable:
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u n",p);
p=p+1;
printf("After increment: Address of p variable is %u n",p); // in our cas
e, p will get incremented by 4 bytes.
return 0;
}
Traversing an array by using pointer
#include<stdio.h>
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}
Decrementing Pointer in C
• Like increment, we can decrement a pointer variable. If we
decrement a pointer, it will start pointing to the previous
location.
• The formula of decrementing the pointer is given
below:
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.
Example: Decrementing of pointer
#include <stdio.h>
void main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u n",p);
p=p-1;
printf("After decrement: Address of p variable is %u n",p); /
/ P will now point to the immediate previous location.
}
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(dat
a 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 Addition
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u n",p);
return 0;
}
C Pointer Subtraction
• Like pointer addition, we can subtract a value from the
pointer variable. Subtracting any number from a pointer will
give an address.
• The formula of subtracting value from the pointer
variable is given below:
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.
Example:
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u n",p);
return 0;
}
Comparison between pointers:
Following operations that can never be
performed on pointers are:
• 1. Addition,Multiplication,Division of two pointers.
• 2.Multiplication between pointer and any number.
• 3.Division of pointer by any number.
• Addition of float or double values to the pointer.
Relationship between Arrays and Pointers
• In C language ,there is a very strong relationship between pointers
and arrays .Arrays can created as pointers and vice versa.
• Following are the main points for understanding the relationship of
pointers with arrays:
1.Elements of an array are stored in consecutive memory locations.
2.The name of an array is a constant pointer that points to the first
element of the array. i.e it stores the address of the first element, also
known as the base address of array.
3.According to pointer arithmetic, when a pointer variable is
incremented, it points to the next location of its base type.
Example:
• Int arr[5]; 1000 1004 1008 1012 1016----------1020
• Int *ptr1; //normal pointer
• Ptr1=&arr[0];
• Ptr1++;
• Int arr[5];
• Int *ptr2[5];// pointer to array
• Ptr2=&arr;//point to the complete
• Ptr2++;
EXAMPLE:
• Int ptrarray[5]={10,11,12,13,14};
HERE, ptrarray and & ptrarray[0] represents ??
ANS: SAME ADDRESS
Pointer To Array:
• It is possible to create a pointer that points to a complete array
instead of pointing to the individual element of an array such pointer
is known as pointer to an array.
• NORMAL POINTER
• EX: PROGRAM
• POINTER TO ARRAY
• EX PROGRAM
Multiple indirection(Double pointer)
• If you define a pointer to pointer;
• WHAT WILL HAPPEN?
The first pointer is used to store the address of the variable
and second pointer is used to store the address of the first
pointer.
Int x=10; Int *ptr1; ptr1=&x;
int **ptr; Ptr=&ptr1;
Declaration: int **ptr;
EXAMPLE:
1.Program to find length of the string.
2.Program to compare strings using pointers.
3.Program to write Function to sort the numbers using pointers.
DYNAMIC MEMORY ALLOCATION: Concept
DMA: Dynamic Memory Allocation
• C Dynamic Memory Allocation can be defined as a procedure
in which the size of a data structure (like Array) is changed
during the runtime.
• C provides some functions to achieve these tasks. There are 4
library functions provided by C defined under <stdlib.h> header
file to facilitate dynamic memory allocation in C programming.
They are:
1.malloc()
2.calloc()
3.free()
4.realloc()
malloc():
• “malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the
specified size.
• It returns a pointer of type void which can be cast into a pointer of
any form. It initializes each block with default garbage value.
• Syntax:
ptr = (cast-type*) malloc(byte-size)
Example: ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the
address of the first byte in the allocated memory.
calloc():
• calloc” or “contiguous allocation” method in C is used to
dynamically allocate the specified number of blocks of memory
of the specified type.
• It initializes each block with a default value ‘0’.
Syntax: ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for 25
elements each with the size of the float.
DMA:EXAMPLE
• #include <stdio.h>#include<stdlib.h>main(){ int i; int
*ptr=(int*)malloc(2*sizeof(int)); //allocate 2 elements
if(ptr==NULL) { printf("memory is not available"); exit(1); }
printf("enter 2 no's:n"); for(i=0;i<2;i++) { scanf("%d",ptr+i); }
ptr=(int*) realloc(ptr,4*sizeof(int)); if(ptr==NULL) {
printf("memory is not available"); exit(1); } printf("enter 2
no's:n"); for(i=2;i<4;i++) //change in the for loop {
scanf("%d",ptr+i); } for(i=0;i<4;i++) //change in the for loop
{ printf("%d",*(ptr+i)); } return 0;
free():
• “free” method in C is used to dynamically de-allocate the
memory.
• The memory allocated using functions malloc() and calloc() is
not de-allocated on their own.
• Hence the free() method is used, whenever the dynamic
memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
• Syntax: free(ptr())
THINGS TO DO : TO MAKE YOURSELF HAPPY
AND POSITIVE
THANK YOU

More Related Content

What's hot

Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
shaibal sharif
 
OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - Lab
Victer Paul
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 
Cache memory
Cache memoryCache memory
Cache memory
Ansari Maviya
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
CPM AND PERT NETWORK DIAGRAM
CPM AND PERT NETWORK DIAGRAMCPM AND PERT NETWORK DIAGRAM
CPM AND PERT NETWORK DIAGRAM
INDRAKUMAR PADWANI
 
Attributes of Output Primitives
Attributes of Output PrimitivesAttributes of Output Primitives
Attributes of Output Primitives
Renita Santhmayora
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
contiguous memory allocation.pptx
contiguous memory allocation.pptxcontiguous memory allocation.pptx
contiguous memory allocation.pptx
Rajapriya82
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
Window to viewport transformation
Window to viewport transformationWindow to viewport transformation
Window to viewport transformation
Ankit Garg
 
Memory allocation (4)
Memory allocation (4)Memory allocation (4)
Memory allocation (4)
rockymani
 
Interrupt
InterruptInterrupt
Interrupt
Joy Sarker
 
Memory management in python
Memory management in pythonMemory management in python
Memory management in python
Gaurav Aggarwal
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 

What's hot (20)

Function overloading
Function overloadingFunction overloading
Function overloading
 
10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil10. Search Tree - Data Structures using C++ by Varsha Patil
10. Search Tree - Data Structures using C++ by Varsha Patil
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - Lab
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Cache memory
Cache memoryCache memory
Cache memory
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
CPM AND PERT NETWORK DIAGRAM
CPM AND PERT NETWORK DIAGRAMCPM AND PERT NETWORK DIAGRAM
CPM AND PERT NETWORK DIAGRAM
 
Attributes of Output Primitives
Attributes of Output PrimitivesAttributes of Output Primitives
Attributes of Output Primitives
 
Java Streams
Java StreamsJava Streams
Java Streams
 
contiguous memory allocation.pptx
contiguous memory allocation.pptxcontiguous memory allocation.pptx
contiguous memory allocation.pptx
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
 
Window to viewport transformation
Window to viewport transformationWindow to viewport transformation
Window to viewport transformation
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Memory allocation (4)
Memory allocation (4)Memory allocation (4)
Memory allocation (4)
 
Interrupt
InterruptInterrupt
Interrupt
 
Memory management in python
Memory management in pythonMemory management in python
Memory management in python
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 

Similar to FYBSC(CS)_UNIT-1_Pointers in C.pptx

pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
Osmania University
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
SwapnaliPawar27
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
aarockiaabinsAPIICSE
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
sajinis3
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Jayanshu Gundaniya
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)Mohd Effandi
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
AtharvPotdar2
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
Ananthi Palanisamy
 
Session 5
Session 5Session 5
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 

Similar to FYBSC(CS)_UNIT-1_Pointers in C.pptx (20)

Pointers
PointersPointers
Pointers
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
 
Session 5
Session 5Session 5
Session 5
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 

More from sangeeta borde

Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptxCH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
sangeeta borde
 
UNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptxUNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptx
sangeeta borde
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
sangeeta borde
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
sangeeta borde
 
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
sangeeta borde
 

More from sangeeta borde (7)

Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptxCH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
CH2_CYBER_SECURITY_FYMSC(DS)-MSC(CS)-MSC(IMCA).pptx
 
UNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptxUNIT-5_Array in c_part1.pptx
UNIT-5_Array in c_part1.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
3. Test Scenarios & Test Cases with Excel Sheet Format (1).pdf
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
2022-23TYBSC(CS)-PYTHON_PROG_ControlStructure.pptx
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 

FYBSC(CS)_UNIT-1_Pointers in C.pptx

  • 2. SYLLABUS: ”Advance C Programming” SEM-II CH.1 POINTERS CH.2 STRINGS CH.3 STRUCTURES AND UNION CH.4 FILE HANDLING CH.5 PREPROCESSOR
  • 3. Chapter 1 :Pointers • Chapter 1 :Pointers • 1.1. Introduction to Pointers. • 1.2. Declaration, definition, initialization, dereferencing. • 1.3. Pointer arithmetic. • 1.4. Relationship between Arrays & Pointers- Pointer to array, Array of pointers. • 1.5. Multiple indirection (pointer to pointer). • 1.6. Functions and pointers- Passing pointer to function, Returning pointer from function, Function pointer. • 1.7. Dynamic memory management- Allocation(malloc(),calloc()), Resizing(realloc()), Releasing(free())., • 1.8. Memory leak, dangling pointers. • 1.9. Types of pointers.
  • 5. INTRODUCTION: • Pointers in C are easy and fun to learn. • Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. • So it becomes necessary to learn pointers to become a perfect C programmer.
  • 6. INTRODUCTION: continue… • 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. • As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
  • 7. Example: #include <stdio.h> int main () { int var1; char var2[10]; printf("Address of var1 variable: %xn", &var1 ); printf("Address of var2 variable: %xn", &var2 ); return 0; }
  • 8. Definition,Declaration,Initialization, Dereferencing of pointers. • Definition of pointers: • A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. • Other Definitions: 1.Pointer is a variable that holds memory address. 2.Pointer is a variable which holds the address of another variable. It contains the memory location of the variable instead of its content.
  • 9. How to Use Pointers • There are a few important operations, which we will do with the help of pointers very frequently. • (a) We define a pointer variable, • (b) assign the address of a variable to a pointer and • (c) finally access the value at the address available in the pointer variable. • This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
  • 10. Declaration of Pointer • The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer. 1.int *a;//pointer to int 2.char *c; 3.float *d//pointer to float
  • 11. Example 1: #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 address of the number therefore printing p gives the address of number . printf("Value of p variable is %d n",*p); //Here we will get the value stored at the address contained by p. return 0; }
  • 12. Initialization of Pointers • When we declare a pointer variable it contains garbage value. i.e. It may be pointing anywhere in the memory. So we should always assign an address before using it in the program. • Pointer initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of the same data type. • Syntax: • <pointer declaration> • Pointer_name =&variable<address of avariable>
  • 13. Initialization of Pointers-Example EX1: Int n,*iptr; iPtr=&n; Ex2: Int a=30,*ptr; Ptr=&a; We can also initialize the pointer at the time of declaration. Ex3: Int roll=102,*ptr=&roll; Float sal=5000.00,*fptr=&sal;
  • 14. sizeof() operator in C • The sizeof() operator is commonly used in C. • It determines the size of the expression or the data type specified in the number of char-sized storage units. • The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. • The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
  • 15. Example: 1. sizeof(datatype) 2. Sizeof(pointer variable) #include <stdio.h>int main() { char a='A'; char *ptr; ptr=&a; printf("n sizeof(ptr)=%d", sizeof(ptr)); printf("nsizeof(a)=%d",sizeof(a)); printf("nsizeof(*ptr)=%d",sizeof(*ptr)); return 0;}
  • 16. Use of sizeof() operator • we dynamically allocate the array space by using sizeof() operator: • Example: • int *ptr=malloc(10*sizeof(int)); • We use malloc() function to allocate the memory and returns the pointer which is pointing to this allocated memory. The memory space is equal to the number of bytes occupied by the int data type and multiplied by 10.
  • 17. Dereferencing of Pointers: • When indirection operator (*) is used with the pointer variable, then it is known as dereferencing a pointer. • When we dereference a pointer, then the value of the variable pointed by this pointer will be returned.
  • 18. Differencing Pointer or Subtraction of pointer from another pointer: • Pointer variable can be subtracted from another pointer variable only if they point to the elements of the same array. • Syntax: • Ptr_variable2-ptr_variable1
  • 19. Why we use dereferencing pointer? • Dereference a pointer is used because of the following reasons: • It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer. • Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.
  • 20. Example: Dereferencing of pointer #include <stdio.h> int main() { int x=9; int *ptr; ptr=&x; *ptr=8; //*ptr will update the value of x printf("value of x is : %d", x); return 0; }
  • 21. Example 2: #include <stdio.h> int main() { int a=90; int *ptr1,*ptr2; ptr1=&a; ptr2=&a; *ptr1=7; *ptr2=6; printf("The value of a is : %d",a); return 0; }
  • 22. Pointer Arithmetic • 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.
  • 23. Following arithmetic operations are possible on the pointer in C language: • Increment • Decrement • Addition • Subtraction • Comparison
  • 24. Incrementing Pointer in C • If we increment a pointer by 1, the pointer will start pointing to the immediate next location. • This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of the data type. • We can traverse an array by using the increment operation on a pointer which will keep pointing to every element of the array, perform some operation on that, and update itself in a loop.
  • 25. The Rule to increment the pointer is given below: Syntax: new_address= current_address + i * size_of(data type) • Where i is the number by which the pointer get increased. • pe to which the pointer is pointing.
  • 26. Example: Incrementing a pointer Variable: #include<stdio.h> int main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable printf("Address of p variable is %u n",p); p=p+1; printf("After increment: Address of p variable is %u n",p); // in our cas e, p will get incremented by 4 bytes. return 0; }
  • 27. Traversing an array by using pointer #include<stdio.h> #include<stdio.h> void main () { int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; int i; printf("printing array elements...n"); for(i = 0; i< 5; i++) { printf("%d ",*(p+i)); } }
  • 28. Decrementing Pointer in C • Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the previous location. • The formula of decrementing the pointer is given below: 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.
  • 29. Example: Decrementing of pointer #include <stdio.h> void main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable printf("Address of p variable is %u n",p); p=p-1; printf("After decrement: Address of p variable is %u n",p); / / P will now point to the immediate previous location. }
  • 30. 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(dat a 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.
  • 31. C Pointer Addition #include<stdio.h> int main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable printf("Address of p variable is %u n",p); p=p+3; //adding 3 to pointer variable printf("After adding 3: Address of p variable is %u n",p); return 0; }
  • 32. C Pointer Subtraction • Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer will give an address. • The formula of subtracting value from the pointer variable is given below: 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.
  • 33. Example: #include<stdio.h> int main() { int number=50; int *p;//pointer to int p=&number;//stores the address of number variable printf("Address of p variable is %u n",p); p=p-3; //subtracting 3 from pointer variable printf("After subtracting 3: Address of p variable is %u n",p); return 0; }
  • 35. Following operations that can never be performed on pointers are: • 1. Addition,Multiplication,Division of two pointers. • 2.Multiplication between pointer and any number. • 3.Division of pointer by any number. • Addition of float or double values to the pointer.
  • 36. Relationship between Arrays and Pointers • In C language ,there is a very strong relationship between pointers and arrays .Arrays can created as pointers and vice versa. • Following are the main points for understanding the relationship of pointers with arrays: 1.Elements of an array are stored in consecutive memory locations. 2.The name of an array is a constant pointer that points to the first element of the array. i.e it stores the address of the first element, also known as the base address of array. 3.According to pointer arithmetic, when a pointer variable is incremented, it points to the next location of its base type.
  • 37. Example: • Int arr[5]; 1000 1004 1008 1012 1016----------1020 • Int *ptr1; //normal pointer • Ptr1=&arr[0]; • Ptr1++; • Int arr[5]; • Int *ptr2[5];// pointer to array • Ptr2=&arr;//point to the complete • Ptr2++;
  • 38. EXAMPLE: • Int ptrarray[5]={10,11,12,13,14}; HERE, ptrarray and & ptrarray[0] represents ?? ANS: SAME ADDRESS
  • 39. Pointer To Array: • It is possible to create a pointer that points to a complete array instead of pointing to the individual element of an array such pointer is known as pointer to an array. • NORMAL POINTER • EX: PROGRAM • POINTER TO ARRAY • EX PROGRAM
  • 40. Multiple indirection(Double pointer) • If you define a pointer to pointer; • WHAT WILL HAPPEN? The first pointer is used to store the address of the variable and second pointer is used to store the address of the first pointer. Int x=10; Int *ptr1; ptr1=&x; int **ptr; Ptr=&ptr1; Declaration: int **ptr;
  • 41. EXAMPLE: 1.Program to find length of the string. 2.Program to compare strings using pointers. 3.Program to write Function to sort the numbers using pointers.
  • 43. DMA: Dynamic Memory Allocation • C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed during the runtime. • C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: 1.malloc() 2.calloc() 3.free() 4.realloc()
  • 44. malloc(): • “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. • It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with default garbage value. • Syntax: ptr = (cast-type*) malloc(byte-size) Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 45. calloc(): • calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. • It initializes each block with a default value ‘0’. Syntax: ptr = (float*) calloc(25, sizeof(float)); • This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 46. DMA:EXAMPLE • #include <stdio.h>#include<stdlib.h>main(){ int i; int *ptr=(int*)malloc(2*sizeof(int)); //allocate 2 elements if(ptr==NULL) { printf("memory is not available"); exit(1); } printf("enter 2 no's:n"); for(i=0;i<2;i++) { scanf("%d",ptr+i); } ptr=(int*) realloc(ptr,4*sizeof(int)); if(ptr==NULL) { printf("memory is not available"); exit(1); } printf("enter 2 no's:n"); for(i=2;i<4;i++) //change in the for loop { scanf("%d",ptr+i); } for(i=0;i<4;i++) //change in the for loop { printf("%d",*(ptr+i)); } return 0;
  • 47. free(): • “free” method in C is used to dynamically de-allocate the memory. • The memory allocated using functions malloc() and calloc() is not de-allocated on their own. • Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. • Syntax: free(ptr())
  • 48. THINGS TO DO : TO MAKE YOURSELF HAPPY AND POSITIVE