SlideShare a Scribd company logo
Pointers in C
1
Vijayananda Ratnam Ch,
Asst. Professor,
Dept. of CSE,
VVIT – Guntur.
Introduction
2
 Pointers are among C’s most powerful, yet most difficult concepts to master
 Some tasks like dynamic memory allocation done only by using pointers. So
it is essential to learn pointers.
 Pointers are a type of variable, just like int, double, etc., except instead of
storing a value, they store a memory address of another variable.
(or)
 Pointer is a variable that stores the address of the other variable.
 In this sense, a variable directly references a value, and a pointer indirectly
references a value.
 The goal of the pointer is to save memory space and perform faster
execution.
 The size of the pointer in C is 8 bytes but on a 32-bit machine, they take up
to 4 bytes.
How does Pointer Works?
3
 If we declare a variable x of type Integer (int) then x will actually store the
value.
int x= 1;
x is equal to one now.
 But, every variable has both value and address, and that address can be
retrieved by putting an ampersand (&) before the variable name like this.
"&x"
 If you are willing to print an address of a variable that address may be a
random number and that random number will be different whenever you
run your program. which means the same program may give different
outputs.
How does Pointer Works?
(cont.)
4
Example:
#include<stdio.h>
int main()
{
int x=1;
printf(“%d”, &x);
return 0;
}
 Output: 6422040 and if you run the same code for the second time the
output may be different.
 In simple terms, variable store values and pointers store the address of
the variable.
Pointer Declaration
5
 Like variables, pointers should be declared before using it in the
program. We can name pointers anything as long as they obey C’s
naming rules.
 Syntax:
datatype *pointer_variable_name;
 Example:
int *ptr;
 Here, ptr is a pointer variable of type integer which holds the address of
any integer variable.
Initializing a pointer
6
 After declaring a pointer, we have to initialize the pointer with the standard
variable address.
 If pointers are not initialized then there may be a problem in the output.
Syntax:
pointer_var_name= &variable;
Example:
ptr= &v;
 Here, the address of integer variable ‘v’ is assigned to pointer variable
‘ptr’.
Examples
7
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */
double *T /* T is a double pointer */
Complex example:
int *AP[5]; /* AP is an array of 5 pointers to ints */
How to Use Pointers?
8
a) First 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.
9
#include <stdio.h>
int main () {
int v = 50; /* actual variable
declaration */
int *ptr; /* pointer variable declaration */
ptr = &v; /* store address of v in pointer variable*/
printf("Address of var variable: %un", &v);
/* address stored in pointer variable */
printf("Address stored in ptr variable: %unn", ptr );
printf("Value of v: %dn", v );
/* access the value of v using the pointer */
printf("Value pointed by *ptr variable: %dn", *ptr );
return 0;
Output:
Address of var variable: 6422036
Address stored in ptr variable:
6422036
Value of v: 50
Value pointed by *ptr variable: 50
Address (&) Operator
10
 The address of (&) operator can be used in front of any variable
object in C -- that returns the location in memory of the variable
 Syntax:
&VariableReference;
Examples:
int V;
int *P;
int A[5];
 &V - memory location of integer variable V
 &(A[2]) - memory location of array element 2 in array A
 &P - memory location of pointer variable P
Indirection (*) Operator
11
 It is also called as Value at address or dereferencing operator
 A pointer variable contains a memory address.
 To refer to the contents of the variable that the pointer points to, we
use indirection operator.
Syntax:
*PointerVariable;
Example:
int v = 50;
int *ptr = &v
// Then *ptr would refer to the contents of the variable v (in this case, the integer
50.)
printf(“%d”,*P); /* Prints 50 */
Sample pointer code snippet.
12
int A = 3;
int B;
int *P = &A;
int *Q = P;
int *R = &B;
printf(“Enter value:“);
scanf(“%d”,R);
printf(“%d %dn”,A,B);
printf(“%d %d %dn”,
*P,*Q,*R);
Q = &B;
if (P == Q)
printf(“1n”);
if (Q == R)
printf(“2n”);
if (*P == *Q)
printf(“3n”);
if (*Q == *R)
printf(“4n”);
if (*P == *R)
printf(“5n”);
Pointer to pointer
13
 A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
 When we define a pointer to a pointer, the first pointer contains the address
of the second pointer, which points to the location that contains the actual
value as shown below.
 Pointer to pointer relations can be applied up to 12 stages but generally,
there is no limitation.
 When we are increasing the pointer to pointer relations, then performance
will be decreased.
Syntax:
datatype **var;
Pointer to pointer…
14
Example:
int v = 50;
int *ptr;
int **ptr;
ptr = &v; /* ptr points the address of v */
pptr = &ptr; /* pptr points the address of ptr using address of
operator & */
printf(“%d %d %dn”, v,*ptr,**pptr); /* prints 50 3 times */
Address of and Dereference operators
15
 The address of (&) and dereference (*) operators are actually
inverses of each other.
 They cancel each other out.
Example:
*&myVar == myVar
and
&*yPtr == yPtr
L and R values
16
 L-value is something that can appear on the left side of an equal sign ( =
).
A place i.e. memory location for a value to be stored
 R-value is something that can appear on the right side of an equal sign (
= ).
A value
 Example:
a = b+25 vs b+25 = a.
Types of Pointers
17
There are eight different types of pointers. They are:
1. Null pointer
2. Void pointer
3. Wild pointer
4. Dangling pointer
5. Complex pointer
6. Near pointer
7. Far pointer
8. Huge pointer
NULL Pointer
18
 NULL Pointer is a pointer which is pointing to nothing. In case, if we
don’t have address to be assigned to a pointer, then we can simply
use NULL.
 A NULL pointer always contains value 0.
 Some advantages of Null pointer are:
 We can initialize a pointer variable when that pointer variable is not assigned any
actual memory address.
 We can pass a null pointer to a function argument when we are not willing to pass
any actual memory address.
Example 1: Example 2:
int *ptr = NULL; //null pointer
printf("The value inside ptr is:%dn",ptr);
//prints 0
int fun(int *ptr)
{
return 15;
}
fun(NULL);
Casting operators
19
 When assigning a memory address of a variable of one type to a
pointer that points to another type it is best to use the cast operator
to indicate the cast is intentional (this will remove the warning)
Example:
int V = 50;
float *P = (float *) &V; /* Casts int address to float * */
 Removes warning, but is still a somewhat unsafe thing to do.
Void pointer
20
 The void pointer is a pointer that is not allied with any data types. This points to some
data location within the storage which doesn’t have any specific type.
 It is also known as a generic pointer.
 If we assign address of char data type to void pointer it will become char Pointer, if int
data type then int pointer and so on.
 It is created by using the keyword void.
 A void pointer cannot be dereferenced.
21
Let us consider the following code snippet to understand how void pointers works:
#include <stdio.h>
int main()
{
int x= 10;
char y= 'a';
void *ptr = &x; // void pointer contains address of int x
// (int *) ptr - does type casting of void.
// *((int*)ptr) dereferences the typecasted void pointer variable.
printf("Integer variable is = %d", *( (int*) ptr) );
ptr = &y; //void pointer holds of char y.
printf("ncharacter variable is= %c", *( (char*) ptr) );
return 0;
}
Wild pointer
22
 Pointers that are not initialized are called wild pointers.
 This pointer may be initialized to a non-NULL garbage value which may not be
a valid address.
 Because they may point to some unknown memory location which may cause
problems in our program. This may lead to the crashing of the program.
Example :
int main()
{
int *p; // wild pointer
*p= 10;
printf("%d",ptr);
return 0;
}
Note: This pointer becomes wild pointer until it points to a normal variable
Dangling pointer
23
 A pointer that points to a memory location that has been deleted (freed) is called a
dangling pointer.
 There are three different ways where Pointer acts as dangling pointer
1. De-allocation of memory.
2. Function call.
3. Variable goes out of scope.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
// After below free call, ptr becomes a dangling pointer
free(ptr);
// No more a dangling pointer
ptr = NULL;
}
24
 These are some old concepts used in 16 bit intel architectures in the days of MS DOS,
not much useful anymore.
 In TURBO C there are three types of pointers. TURBO C works under DOS operating
system which is based on 8085 microprocessor.
1. Near pointer
2. Far pointer
3. Huge pointer
 Near pointer is used to store 16 bit addresses means within current segment on a 16
bit machine. The limitation is that we can only access 64kb of data at a time.
 A far pointer is typically 32 bit that can access memory outside current segment. To
use this, compiler allocates a segment register to store segment address, then another
register to store offset within current segment.
 Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In
case of far pointers, a segment is fixed. In far pointer, the segment part cannot be
modified, but in Huge it can be.
Near, Far and Huge
pointers
Constant Pointers
25
 Const Pointers, just like any const variable, is unable to be
changed once it is initialized.
 A constant pointer is one that cannot change the address it
contains. In other words, we can say that once a constant pointer
points to a variable, it cannot point to any other variable.
 Const Pointers are Pointers that always point to the same memory
location.
 These must be initialized when they are declared.
Syntax:
 <type of pointer> *const <pointer name>;
Example:
 int *const ptr;
26
Let us consider the following example to understand how constant
pointers works:
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
//Definition of constant constant
int *const ptr = &a; //Now, ptr is pointing to the value of the variable a.
*ptr = 30; // Works, since the pointer pointing to the value is not
constant.
ptr = &b; //Error: Now, ptr is pointing to the value of the variable b.
return 0;
}
Constant Pointers…
Pointer to constant
27
 As the name itself indicates, the value of the variable to which
the pointer is pointing, is constant.
 In other words, a pointer through which one cannot change the
value of the variable to which it points is known as a pointer to
constant.
Syntax:
const <type of pointer> *<pointer name>;
Example:
const int *ptr;
28
Let us consider the example given below to understand how a pointer to
constant works:
#include <stdio.h>
int main( )
{
int a = 10;
//Definition of pointer to constant
const int* ptr = &a; //Now, ptr is pointing to the value of the variable a.
*ptr = 30; //Error: Since the value is constant.
return 0;
}
 In the above code, in Line No. 7, we are trying to change the value of the variable
to which the pointer is pointing to, but this is not possible since the value is
Pointer to constant…
Pointer arithmetic
29
 Welcome to the world of weird programming errors.
 This is another example of the powerful but dangerous
nature of pointers.
 Pointer Arithmetic is so error prone, it’s not allowed in
Java or C#.
 This doesn’t mean don’t use – you may have, or at least
understand it so you can understand other people’s
code. So master this.
Pointer arithmetic…
30
 Pointer is a variable that points to a memory location. Memory
addresses are numeric value that ranges from zero to maximum
memory size in bytes.
 These addresses can be manipulated like simple variables. You can
increment, decrement, calculate or compare these addresses manually.
 You can perform a limited number of arithmetic operations on pointers.
These operations are:
 Increment (++)
 Decrement (--)
 Addition (+)
 Subtraction (-)
 Comparison (>, >=, <, <=, ==, !=)
Pointer arithmetic…
31
Pointer increment and decrement:
 Increment (++) operator when used with a pointer variable returns next address
pointed by the pointer.
 The next address returned is the sum of current pointed address and size of
pointer data type.
 Similarly, decrement operator returns the previous address pointed by the
pointer.
 The returned address is the difference of current pointed address and size of
pointer data type.
 The Rule to increment/decrement the pointer is given below:
 Where n is the number by which the pointer get increased.
new_address= current_address ± n * size_of(data type)
Pointer arithmetic…
32
 Let's see the example of incrementing and decrementing pointer
variable.
#include<stdio.h>
int main()
{
int v=50;
int *ptr; //pointer to int
ptr=&v; //Stores the address of variable v
printf("Address of p variable is %u n",p);
p++;
printf("After increment: Address of p variable is %u n",p);
p--;
printf("After decrement: Address of p variable is %u n",p);
return 0;
}
33
Expression
Assuming p is a
pointer to a…
…and the size
of *p is…
Value added to
the pointer
p+1 char 1 1
p+1 short 2 2
p+1 int 4 4
p+1 double 8 8
p+2 char 1 2
p+2 short 2 4
p+2 int 4 8
p+2 double 8 16
Pointer arithmetic…
34
Pointer comparison:
 You can compare two pointers with the following operators: ==, !=, <, >, <=,
and >=.
 The == and != operators are used to compare two pointers whether they
contain the same address or not.
 Two pointers are equal when they both are null, or contains the address of
the same variable.
 Use of these (i.e. == and !=) operators are valid only when pointers are of
the same base type, or between a null pointer and any other pointer, or void
pointer and any other pointer.
 Pointer comparisons can be performed even when the pointers point to
elements of different arrays.
Pointer arithmetic…
35
#include<stdio.h>
int main() {
int a = 12, b=12;
int *ptr1, *ptr2;
ptr1 = &a;
ptr2 = &b,
printf("address of a = %un", ptr1);
printf("address of b = %un", ptr2);
if (ptr1==ptr2)
printf("Addresses are samen");
else
printf("Addresses are differentn");
if (*ptr1==*ptr2)
printf("Values are samen");
else
printf("Values are differentn");
return 0;
}
Let's see the example of comparison of two pointer variables.
lllegal arithmetic with pointers
36
 There are various operations which can not be performed on pointers.
Since, pointer stores address hence we must ignore the operations which
may lead to an illegal address.
 A list of such operations is given below.
 Address + Address = illegal
 Address * Address = illegal
 Address % Address = illegal
 Address / Address = illegal
 Address & Address = illegal
 Address ^ Address = illegal
 Address | Address = illegal
 ~Address = illegal
Pointer to an array
 So again, what is an array really?
 That’s right, a const pointer to the first element of the array.
 So, we can create a Pointer to the first element of an array with
code like
int b[5] = { 10,5,18,33,21 };
int *p;
p = b; //equivalent to p = &b[0];
 p is a pointer to &b[0], which is the address of the first element of
the array b.
Pointer to an array…
 Normally, when we would want to access the 4th element in our array, we’d use notation
like b[3];
but, we can also do
( p + 3 ); //actually does address of p + 3 * 4
This is called using Pointer/Offset notation.
We can also access pointers using subscripts
p[3]; // same as above
This is called, Pointer/Subscript notation.
 Once you store the address of the first element in 'p', you can access the array
elements using *p, *(p+1), *(p+2) and so on.
Pointer to an array…
39
Given below is the example to show all the concepts discussed above
−int main() {
int b[5]={10,5,18, 33,21}; /* an array with 5 elements */
int *p;
int i;
p = b; //address of first element is assigned to p
printf("Array values using pointersn");
for ( i = 0; i < 5; i++ )
printf("*(p + %d) : %dn", i, *(p + i) );
printf( "Array values using b as addressn");
for ( i = 0; i < 5; i++ )
printf("*(b + %d) : %dn", i, *(b + i) );
return 0;
}
1D Array and Pointers Example
float A[6] = {1.0, 2.0, 1.0, 0.5, 3.0, 2.0};
float *theMin = &(A[0]);
float *walker = &(A[1]);
while (walker < &(A[6]))
{
if (*walker < *theMin)
theMin = walker;
walker = walker + 1;
}
printf("%.1fn",*theMin);
Combining Indirection operator (*) and Inc/Dec operator
41
 While processing elements of an array, C programmers often mix indirection
operator (*) and increment/decrement operator( ++ and -- ).
 Suppose x is integer variable and p is a pointer to int. Now consider the
following statements and try to interpret them.
Example 1:
Example 2:
Example 3:
x = *p++;
x = *++p;
x = ++*p;

More Related Content

What's hot

Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
Md. Afif Al Mamun
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
C pointer
C pointerC pointer
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
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
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Pointer in c
Pointer in cPointer in c
Pointer in c
Imamul Kadir
 
Pointers
PointersPointers
Pointers
sarith divakar
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
Structure in C
Structure in CStructure in C
Structure in C
Fazle Rabbi Ador
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
Dr-Dipali Meher
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Rajat Busheheri
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
ShivanshuVerma11
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
madan reddy
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
rgnikate
 
Pointer in c
Pointer in cPointer in c
Pointer in c
lavanya marichamy
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
sai tarlekar
 

What's hot (20)

Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
C pointer
C pointerC pointer
C pointer
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
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...
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointers
PointersPointers
Pointers
 
C Pointers
C PointersC Pointers
C Pointers
 
Structure in C
Structure in CStructure in C
Structure in C
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Fundamentals of Pointers in C
Fundamentals of Pointers in CFundamentals of Pointers in C
Fundamentals of Pointers in C
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Chap 11(pointers)
Chap 11(pointers)Chap 11(pointers)
Chap 11(pointers)
 

Similar to Pointers in C

PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
TamiratDejene1
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
janithlakshan1
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
Pointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptxPointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptx
ahmedbadr608094
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
C programming session8
C programming  session8C programming  session8
C programming session8
Keroles karam khalil
 
C programming session8
C programming  session8C programming  session8
C programming session8
Keroles karam khalil
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
Gamindu Udayanga
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
ajajkhan16
 
SPC Unit 3
SPC Unit 3SPC Unit 3
SPC Unit 3
SIMONTHOMAS S
 
Pointers
PointersPointers
Pointers
Swarup Boro
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
sudhakargeruganti
 
Pointers
PointersPointers
Pointers
Prasadu Peddi
 
Pointers in c
Pointers in cPointers in c
Pointers in c
CHANDAN KUMAR
 
Pointer
PointerPointer
Types of pointer
Types of pointerTypes of pointer
Types of pointer
Ravindra Nikate
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
Ramakrishna Reddy Bijjam
 

Similar to Pointers in C (20)

PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Chapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdfChapter 5 (Part I) - Pointers.pdf
Chapter 5 (Part I) - Pointers.pdf
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Pointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptxPointers_in_c_2024.01.10_embedded _c.pptx
Pointers_in_c_2024.01.10_embedded _c.pptx
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
SPC Unit 3
SPC Unit 3SPC Unit 3
SPC Unit 3
 
Pointers
PointersPointers
Pointers
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Pointers
PointersPointers
Pointers
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointer
PointerPointer
Pointer
 
Types of pointer
Types of pointerTypes of pointer
Types of pointer
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
 

Recently uploaded

How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
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.
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
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
 
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
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
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
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
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
 
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
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 

Pointers in C

  • 1. Pointers in C 1 Vijayananda Ratnam Ch, Asst. Professor, Dept. of CSE, VVIT – Guntur.
  • 2. Introduction 2  Pointers are among C’s most powerful, yet most difficult concepts to master  Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.  Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable. (or)  Pointer is a variable that stores the address of the other variable.  In this sense, a variable directly references a value, and a pointer indirectly references a value.  The goal of the pointer is to save memory space and perform faster execution.  The size of the pointer in C is 8 bytes but on a 32-bit machine, they take up to 4 bytes.
  • 3. How does Pointer Works? 3  If we declare a variable x of type Integer (int) then x will actually store the value. int x= 1; x is equal to one now.  But, every variable has both value and address, and that address can be retrieved by putting an ampersand (&) before the variable name like this. "&x"  If you are willing to print an address of a variable that address may be a random number and that random number will be different whenever you run your program. which means the same program may give different outputs.
  • 4. How does Pointer Works? (cont.) 4 Example: #include<stdio.h> int main() { int x=1; printf(“%d”, &x); return 0; }  Output: 6422040 and if you run the same code for the second time the output may be different.  In simple terms, variable store values and pointers store the address of the variable.
  • 5. Pointer Declaration 5  Like variables, pointers should be declared before using it in the program. We can name pointers anything as long as they obey C’s naming rules.  Syntax: datatype *pointer_variable_name;  Example: int *ptr;  Here, ptr is a pointer variable of type integer which holds the address of any integer variable.
  • 6. Initializing a pointer 6  After declaring a pointer, we have to initialize the pointer with the standard variable address.  If pointers are not initialized then there may be a problem in the output. Syntax: pointer_var_name= &variable; Example: ptr= &v;  Here, the address of integer variable ‘v’ is assigned to pointer variable ‘ptr’.
  • 7. Examples 7 int *P; /* P is var that can point to an int var */ float *Q; /* Q is a float pointer */ char *R; /* R is a char pointer */ double *T /* T is a double pointer */ Complex example: int *AP[5]; /* AP is an array of 5 pointers to ints */
  • 8. How to Use Pointers? 8 a) First 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.
  • 9. 9 #include <stdio.h> int main () { int v = 50; /* actual variable declaration */ int *ptr; /* pointer variable declaration */ ptr = &v; /* store address of v in pointer variable*/ printf("Address of var variable: %un", &v); /* address stored in pointer variable */ printf("Address stored in ptr variable: %unn", ptr ); printf("Value of v: %dn", v ); /* access the value of v using the pointer */ printf("Value pointed by *ptr variable: %dn", *ptr ); return 0; Output: Address of var variable: 6422036 Address stored in ptr variable: 6422036 Value of v: 50 Value pointed by *ptr variable: 50
  • 10. Address (&) Operator 10  The address of (&) operator can be used in front of any variable object in C -- that returns the location in memory of the variable  Syntax: &VariableReference; Examples: int V; int *P; int A[5];  &V - memory location of integer variable V  &(A[2]) - memory location of array element 2 in array A  &P - memory location of pointer variable P
  • 11. Indirection (*) Operator 11  It is also called as Value at address or dereferencing operator  A pointer variable contains a memory address.  To refer to the contents of the variable that the pointer points to, we use indirection operator. Syntax: *PointerVariable; Example: int v = 50; int *ptr = &v // Then *ptr would refer to the contents of the variable v (in this case, the integer 50.) printf(“%d”,*P); /* Prints 50 */
  • 12. Sample pointer code snippet. 12 int A = 3; int B; int *P = &A; int *Q = P; int *R = &B; printf(“Enter value:“); scanf(“%d”,R); printf(“%d %dn”,A,B); printf(“%d %d %dn”, *P,*Q,*R); Q = &B; if (P == Q) printf(“1n”); if (Q == R) printf(“2n”); if (*P == *Q) printf(“3n”); if (*Q == *R) printf(“4n”); if (*P == *R) printf(“5n”);
  • 13. Pointer to pointer 13  A pointer to a pointer is a form of multiple indirection, or a chain of pointers.  When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.  Pointer to pointer relations can be applied up to 12 stages but generally, there is no limitation.  When we are increasing the pointer to pointer relations, then performance will be decreased. Syntax: datatype **var;
  • 14. Pointer to pointer… 14 Example: int v = 50; int *ptr; int **ptr; ptr = &v; /* ptr points the address of v */ pptr = &ptr; /* pptr points the address of ptr using address of operator & */ printf(“%d %d %dn”, v,*ptr,**pptr); /* prints 50 3 times */
  • 15. Address of and Dereference operators 15  The address of (&) and dereference (*) operators are actually inverses of each other.  They cancel each other out. Example: *&myVar == myVar and &*yPtr == yPtr
  • 16. L and R values 16  L-value is something that can appear on the left side of an equal sign ( = ). A place i.e. memory location for a value to be stored  R-value is something that can appear on the right side of an equal sign ( = ). A value  Example: a = b+25 vs b+25 = a.
  • 17. Types of Pointers 17 There are eight different types of pointers. They are: 1. Null pointer 2. Void pointer 3. Wild pointer 4. Dangling pointer 5. Complex pointer 6. Near pointer 7. Far pointer 8. Huge pointer
  • 18. NULL Pointer 18  NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned to a pointer, then we can simply use NULL.  A NULL pointer always contains value 0.  Some advantages of Null pointer are:  We can initialize a pointer variable when that pointer variable is not assigned any actual memory address.  We can pass a null pointer to a function argument when we are not willing to pass any actual memory address. Example 1: Example 2: int *ptr = NULL; //null pointer printf("The value inside ptr is:%dn",ptr); //prints 0 int fun(int *ptr) { return 15; } fun(NULL);
  • 19. Casting operators 19  When assigning a memory address of a variable of one type to a pointer that points to another type it is best to use the cast operator to indicate the cast is intentional (this will remove the warning) Example: int V = 50; float *P = (float *) &V; /* Casts int address to float * */  Removes warning, but is still a somewhat unsafe thing to do.
  • 20. Void pointer 20  The void pointer is a pointer that is not allied with any data types. This points to some data location within the storage which doesn’t have any specific type.  It is also known as a generic pointer.  If we assign address of char data type to void pointer it will become char Pointer, if int data type then int pointer and so on.  It is created by using the keyword void.  A void pointer cannot be dereferenced.
  • 21. 21 Let us consider the following code snippet to understand how void pointers works: #include <stdio.h> int main() { int x= 10; char y= 'a'; void *ptr = &x; // void pointer contains address of int x // (int *) ptr - does type casting of void. // *((int*)ptr) dereferences the typecasted void pointer variable. printf("Integer variable is = %d", *( (int*) ptr) ); ptr = &y; //void pointer holds of char y. printf("ncharacter variable is= %c", *( (char*) ptr) ); return 0; }
  • 22. Wild pointer 22  Pointers that are not initialized are called wild pointers.  This pointer may be initialized to a non-NULL garbage value which may not be a valid address.  Because they may point to some unknown memory location which may cause problems in our program. This may lead to the crashing of the program. Example : int main() { int *p; // wild pointer *p= 10; printf("%d",ptr); return 0; } Note: This pointer becomes wild pointer until it points to a normal variable
  • 23. Dangling pointer 23  A pointer that points to a memory location that has been deleted (freed) is called a dangling pointer.  There are three different ways where Pointer acts as dangling pointer 1. De-allocation of memory. 2. Function call. 3. Variable goes out of scope. Example: #include<stdio.h> #include<stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)); // After below free call, ptr becomes a dangling pointer free(ptr); // No more a dangling pointer ptr = NULL; }
  • 24. 24  These are some old concepts used in 16 bit intel architectures in the days of MS DOS, not much useful anymore.  In TURBO C there are three types of pointers. TURBO C works under DOS operating system which is based on 8085 microprocessor. 1. Near pointer 2. Far pointer 3. Huge pointer  Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine. The limitation is that we can only access 64kb of data at a time.  A far pointer is typically 32 bit that can access memory outside current segment. To use this, compiler allocates a segment register to store segment address, then another register to store offset within current segment.  Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In case of far pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can be. Near, Far and Huge pointers
  • 25. Constant Pointers 25  Const Pointers, just like any const variable, is unable to be changed once it is initialized.  A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable.  Const Pointers are Pointers that always point to the same memory location.  These must be initialized when they are declared. Syntax:  <type of pointer> *const <pointer name>; Example:  int *const ptr;
  • 26. 26 Let us consider the following example to understand how constant pointers works: #include <stdio.h> int main() { int a = 10; int b = 20; //Definition of constant constant int *const ptr = &a; //Now, ptr is pointing to the value of the variable a. *ptr = 30; // Works, since the pointer pointing to the value is not constant. ptr = &b; //Error: Now, ptr is pointing to the value of the variable b. return 0; } Constant Pointers…
  • 27. Pointer to constant 27  As the name itself indicates, the value of the variable to which the pointer is pointing, is constant.  In other words, a pointer through which one cannot change the value of the variable to which it points is known as a pointer to constant. Syntax: const <type of pointer> *<pointer name>; Example: const int *ptr;
  • 28. 28 Let us consider the example given below to understand how a pointer to constant works: #include <stdio.h> int main( ) { int a = 10; //Definition of pointer to constant const int* ptr = &a; //Now, ptr is pointing to the value of the variable a. *ptr = 30; //Error: Since the value is constant. return 0; }  In the above code, in Line No. 7, we are trying to change the value of the variable to which the pointer is pointing to, but this is not possible since the value is Pointer to constant…
  • 29. Pointer arithmetic 29  Welcome to the world of weird programming errors.  This is another example of the powerful but dangerous nature of pointers.  Pointer Arithmetic is so error prone, it’s not allowed in Java or C#.  This doesn’t mean don’t use – you may have, or at least understand it so you can understand other people’s code. So master this.
  • 30. Pointer arithmetic… 30  Pointer is a variable that points to a memory location. Memory addresses are numeric value that ranges from zero to maximum memory size in bytes.  These addresses can be manipulated like simple variables. You can increment, decrement, calculate or compare these addresses manually.  You can perform a limited number of arithmetic operations on pointers. These operations are:  Increment (++)  Decrement (--)  Addition (+)  Subtraction (-)  Comparison (>, >=, <, <=, ==, !=)
  • 31. Pointer arithmetic… 31 Pointer increment and decrement:  Increment (++) operator when used with a pointer variable returns next address pointed by the pointer.  The next address returned is the sum of current pointed address and size of pointer data type.  Similarly, decrement operator returns the previous address pointed by the pointer.  The returned address is the difference of current pointed address and size of pointer data type.  The Rule to increment/decrement the pointer is given below:  Where n is the number by which the pointer get increased. new_address= current_address ± n * size_of(data type)
  • 32. Pointer arithmetic… 32  Let's see the example of incrementing and decrementing pointer variable. #include<stdio.h> int main() { int v=50; int *ptr; //pointer to int ptr=&v; //Stores the address of variable v printf("Address of p variable is %u n",p); p++; printf("After increment: Address of p variable is %u n",p); p--; printf("After decrement: Address of p variable is %u n",p); return 0; }
  • 33. 33 Expression Assuming p is a pointer to a… …and the size of *p is… Value added to the pointer p+1 char 1 1 p+1 short 2 2 p+1 int 4 4 p+1 double 8 8 p+2 char 1 2 p+2 short 2 4 p+2 int 4 8 p+2 double 8 16
  • 34. Pointer arithmetic… 34 Pointer comparison:  You can compare two pointers with the following operators: ==, !=, <, >, <=, and >=.  The == and != operators are used to compare two pointers whether they contain the same address or not.  Two pointers are equal when they both are null, or contains the address of the same variable.  Use of these (i.e. == and !=) operators are valid only when pointers are of the same base type, or between a null pointer and any other pointer, or void pointer and any other pointer.  Pointer comparisons can be performed even when the pointers point to elements of different arrays.
  • 35. Pointer arithmetic… 35 #include<stdio.h> int main() { int a = 12, b=12; int *ptr1, *ptr2; ptr1 = &a; ptr2 = &b, printf("address of a = %un", ptr1); printf("address of b = %un", ptr2); if (ptr1==ptr2) printf("Addresses are samen"); else printf("Addresses are differentn"); if (*ptr1==*ptr2) printf("Values are samen"); else printf("Values are differentn"); return 0; } Let's see the example of comparison of two pointer variables.
  • 36. lllegal arithmetic with pointers 36  There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address.  A list of such operations is given below.  Address + Address = illegal  Address * Address = illegal  Address % Address = illegal  Address / Address = illegal  Address & Address = illegal  Address ^ Address = illegal  Address | Address = illegal  ~Address = illegal
  • 37. Pointer to an array  So again, what is an array really?  That’s right, a const pointer to the first element of the array.  So, we can create a Pointer to the first element of an array with code like int b[5] = { 10,5,18,33,21 }; int *p; p = b; //equivalent to p = &b[0];  p is a pointer to &b[0], which is the address of the first element of the array b.
  • 38. Pointer to an array…  Normally, when we would want to access the 4th element in our array, we’d use notation like b[3]; but, we can also do ( p + 3 ); //actually does address of p + 3 * 4 This is called using Pointer/Offset notation. We can also access pointers using subscripts p[3]; // same as above This is called, Pointer/Subscript notation.  Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on.
  • 39. Pointer to an array… 39 Given below is the example to show all the concepts discussed above −int main() { int b[5]={10,5,18, 33,21}; /* an array with 5 elements */ int *p; int i; p = b; //address of first element is assigned to p printf("Array values using pointersn"); for ( i = 0; i < 5; i++ ) printf("*(p + %d) : %dn", i, *(p + i) ); printf( "Array values using b as addressn"); for ( i = 0; i < 5; i++ ) printf("*(b + %d) : %dn", i, *(b + i) ); return 0; }
  • 40. 1D Array and Pointers Example float A[6] = {1.0, 2.0, 1.0, 0.5, 3.0, 2.0}; float *theMin = &(A[0]); float *walker = &(A[1]); while (walker < &(A[6])) { if (*walker < *theMin) theMin = walker; walker = walker + 1; } printf("%.1fn",*theMin);
  • 41. Combining Indirection operator (*) and Inc/Dec operator 41  While processing elements of an array, C programmers often mix indirection operator (*) and increment/decrement operator( ++ and -- ).  Suppose x is integer variable and p is a pointer to int. Now consider the following statements and try to interpret them. Example 1: Example 2: Example 3: x = *p++; x = *++p; x = ++*p;