0% found this document useful (0 votes)
19 views

Pointers

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

Pointers

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

POINTERS

Agenda
• Pointers
• Pointer Declaration and Initialization
• Pointer Arithmetic
• Pointer Comparison
• Pointer expressions
• Example Programs
• Benefits of Pointers
• Pointers to Pointers
• Pointers and Arrays
• Pointers and character strings
• Array of Pointers
• Pointers as Function Arguments
• Functions returning Pointers
• Pointers to Functions
• Pointers and Structures
• Trouble with Pointers
• References
Pointers
• A variable that holds a memory address.
• This address is the location of another object in the memory.
• Pointer as an address indicates where to find an object.
• The most useful, powerful and tricky concept in C language.
• Makes C very fast.
• Direct interaction with hardware.
• Solves very complicated programming problems
• Not all pointers actually contain an address.
Example- NULL pointer.
• Value of NULL pointer is 0.
How does a memory look like ?
Address
Locations
X1000

X1004
X1000
X1001
X1008
X1002
X100c X1003

x1010
Operators used in Pointers
Dereferencing Address

(Value at)
&
(Address of)
Int i=3;

Address of ‘i’ Value of ‘i’


‘&i’ variable
‘*i’
i
3
(Value of i)

x1000 x1004 x1008 x100c x1010 x1014

Address of i
The value ‘3’ is saved in the memory location ‘x100c’
Pointer Declaration & Initialization
 When you write int *, compiler assumes that any address that it holds points to an integer
type.
 Eg:- int count, *m;
m= &count;
It means memory address of count variable is stored into m. & is unary operator that
returns the memory address. i.e. & (ampersand) is returning the address.
 It means m receives the address of count.
 Suppose, count uses memory address 2000 to store its value 100.
 So, m=&count means m has address 2000.
 q= *m
it returns the value at address m. value at address 2000 is 100.
so, q will return value 100. count=100
2000
i.e. q receives the value at address m.
 It is possible in some environments to have multiple pointer values
with different representations that point to same location in memory.
Example main()
{
main()
int j=3;
{
printf(“address of j =%u”,&j);
int j=3;
printf(“value of j =%d”,j);
printf(“address of j =%u”,&j);
printf(“value of j =%d”,j); printf(“value of j =%d”,*(&j));
} }
Output: Output:
address of j=65524 address of j=65524
value of j =3 value of j =3
value of j =3
Pointer Arithmetic
• There are only two arithmetic operations that can be used on pointers
– Addition
– Subtraction
• To understand this concept, lets p1 be an integer pointer with value 2000 address.
– int is of 4 bytes
– After expression p1++;
– P1 contains address 2004 not 2001.
• Each time p1 is incremented, it will point to next integer.
• The same is true for decrement.
– for p1--;
– Causes value of p1 to be 1996.
• Each time a pointer is incremented, it points to the memory location of the next element of
its base type.
• If decremented, then it points to previous element location.
• p1=p1+12; makes p1 points to 12th element of p1 type.
Pointer Arithmetic Example 2
Lets take this example program

#include<stdio.h> b=1
void main() b=1+4

{ b= 5

int a [5]={1,2,3,4,5} , b , *pt ;


pt = &a[0]; a[0] a[1] a[2] a[3] a[4]
pt = pt + 4 ; //pt is incremented by 4
x1000 x1004 x1008 x100c x1010
consecutive memory locations pt

b=a[0] ;
a[0] a[1] a[2] a[3] a[4]
b+=4 ; b

} x1000 x1004 x1008 x100c x1010


Arithmetic Rules
• You cannot multiply or divide pointers.
• You cannot add or subtract two pointers.
• You cannot apply bitwise operators to them.
• You cannot add or subtract type float or double to or from pointers.
Pointer Comparison
• You can compare two pointers in a relational expression,
Example:
if(p<q)
printf(“p points to lower memory than q \n”);
• Pointer comparison are useful only when two pointers point to a
common object such as an array.
Pointer Expressions
If p1 and p2 are properly declared and initialized pointers then, ‘C’ allows adding integers to a
pointer variable.

EX:
int a=5, b=10;
int *p1,*p2;
p1=&a;
p2=&b;

Now,
p1=p1+1=1000+2=1002;
p1=p1+2=1000+ (2*2) =1004;
p1=p1+4=1000+ (2*4) =1008;
p2=p2+2=3000+ (2*2) =3004;
p2=p2+6=3000+ (2*6) =3012;
Pointer Expressions
If p1 & p2 are properly declared and initialized, pointers then ‘C’ allows to subtract integers
from pointers. From the above example,

p1=p1-1=1000-2=998;
p1=p1-2=1000-4=996;
p1=p1-4=1000-8=992;
p2=p2-2=3000-4=2996;
p2=p2-6=3000-12=2988;
Pointer Expressions
-> If p1 & p2 are properly declared and initialized pointers, and both points to the elements of
same type. “Subtraction of one pointer from another pointer is also possible".

NOTE: this operation is done when the both pointer variable points to the elements of the
same array.
EX:
p2- p1 (It gives the number of elements between p1 and p2)

-> Pointer can also be used with increment and decrement operators.

int num = 5; // Suppose address of num = 1000


int *ptr; // Pointer variable
ptr = &num; // ptr points to 1000 or ptr points to num
ptr++; // ptr now points to 1002, since integer size is 2 bytes
ptr--; // ptr now points to 1000
Example Program 3
void main()

{
OUTPUT
int num=10; Number = 10

int *pnum=NULL; Pointer Number = 30

pnum = &num;//pnum=address of num

*pnum += 20; //pnum=pnum+20

printf("\nNumber = %d", num);

printf("\nPointer Number = %d", *pnum);

}
Example Program 4
void main()
{
int a[10] = {1,2,3,4,5,6,7,8,9,12} ,*p, *q , i;
OUTPUT
p = &a[2];// address of the element 3
The value of i is 3
q = &a[5]; //address of the element 6 The value of i is -3
i = *q - *p;//6-3 The value of i is 0
printf(“The value of i is %d” i );
i = *p - *q;//3-6
printf(“The value of i is %d” i );
a[2] = a[5] = 0;
i = *p - *q;
printf(“The value of i is %d” i );
}
Example Program 5
void main()
{
int a[10] = { 2,3,4,5,6,7,8,9,1,0 }, *p, *q;
p = &a[2]; // address of 4 OUTPUT
q = p + 3; // address of 7 The value of p and q are : 7 , 7

p = q – 1; // address of 6
p+ + ;//address of 7
printf(“The value of p and q are : %d , %d” *p,*q);
}
Benefits of pointer

• Pointers are used in situations when passing actual values is difficult or not desired.
• To return more than one value from a function.
• They increase the execution speed.
• Pointers are more efficient in handling the data types.
• Pointers reduce the length and complexity of a program.
• Implementing linked lists, trees, graphs and many other data structure.
Pointers to Pointers
• Pointer variable is just a place-holder of an address value, and itself is a variable.
• Hence a pointer can hold address of (point to) another pointer variable. It is called a
“double pointer” or a chain of pointers or a pointer to pointer.
• 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.

• Declaration:
int **var;
• When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice.
Pointers and Arrays
int val[5]={10,20,30,40,50};
int *p

if p = &val[0] which means *p ==val[0]


If (p+1) == &val[2] and *(p+1) == val[2]
If (p+2) == &val[3] and *(p+2) == val[3]

(p+n) == &val[n+1] and *(p+n) == val[n+1]


Example Program 7
/*program to compute sum of all elements stored in an array using pointers*/

#include<stdio.h>
#include<conio.h>
main ()
{
int a [10], I, sum=0,*p;
printf (“enter 10 elements \n”);
for (i=0; i<10; i++)
scanf (“%d”, & a[i]);
p=a;
for (i = 0; i<10; i++)
{
sum = sum+ *p;
p++;
}
printf (“the sum is % d”, sum);
getch ();
}
Example Program 9
#include <stdio.h>
OUTPUT
main(void)
{ HELLO
char str[6] = "HELLO"; // string variable
char *ptr = str; // pointer variable H is stored at 62
int len; E is stored at 63
printf(“%s\n”, str); L is stored at 64
while(*ptr != '\0') // print the string L is stored at 65
{ O is stored at 66
printf("%c is stored at %u", *ptr, ptr);
// move the ptr pointer to the next memory location The length of the string is= 5
ptr++;
}
len=ptr-str;
printf(“The length of the string is= %d\n”, len);
}
Pointers as Function Arguments
• Pointer as a function parameter is used to hold addresses of arguments passed
during function call.
• This is also known as call by reference.
• When a function is called by reference any change made to the reference variable
will effect the original variable.
Example Program 11
/* Program to swap 2 numbers using pointer*/

#include <stdio.h>
void swap(int *a, int *b);
/* pointer 'a' and 'b' holds and points to the address of 'm' and 'n' */
int main() void swap(int *a, int *b)
{ {
int m = 10, n = 20; int temp;
printf("m = %d\n", m); temp = *a;
printf("n = %d\n\n", n); *a = *b;
//passing address of m and n to the swap function *b = temp;
swap(&m, &n); }

printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n); OUTPUT:
return 0;
} m = 10
n = 20
After Swapping:
m = 20
n = 10
Functions returning Pointer variables

• A function can also return a pointer to the calling function.


• It is to be noted that local variables of function doesn't live outside the function.
• They have scope only inside the function.
• Hence if you return a pointer connected to a local variable, that pointer will be pointing to
nothing when the function ends.
• Use argument with functions. Because argument passed to the functions are declared inside
the calling function, hence they will live outside the function as well.
Pointer to functions
• It is possible to declare a pointer pointing to a function which can then be used as an argument
in another function.
• A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
• Eg:
int sum(int, int); //function declaration
int (*s)(); //legal declaration of pointer to function
int *s(); //This is not a declaration of pointer to function. It returns pointer of type int.
.

Pointer to functions
• A function pointer can point to a specific function when it is assigned the name of
that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
• Here, s is a pointer to a function sum. Now sum can be called using function
pointer s along with providing the required argument values.
s (10, 20) ; => sum(10,20);
Example Program 13
#include <stdio.h>

int main( )
{
int s;
int sum(int x, int y); OUTPUT:
int (*fp)(int, int);
fp = sum; 25
s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}

int sum(int x, int y)


{
return x+y;
}
Pointers and Structures
• Name of an array stands for the address of its zeroth element.
• Same applies for the names of arrays of structure variables.
• Eg:
struct inventory
{
char name[30];
int number;
float price;
}product[2], *ptr;
• Here, product is an array of 2 elements, each of type struct inventory and ptr as a
pointer to data objects of type struct inventory.
Pointers and Structures
ptr=product
• Would assign the address of the zeroth element of product to ptr.
• i.e., ptr points to product[0].
• Its members can be accessed using:
ptr->name
ptr->number
ptr->price
• When ptr is incremented by one, it points to the next record. i.e., product[1].
• The following for statement will print the values of members of all the elements of
product array.
for(ptr=product; ptr<product+2; ptr++)
printf(“%s %d %f\n”, ptr->name, ptr->number, ptr->price);
Example Program 14
#include <stdio.h>

struct Book
{
char name[10];
int price;
}b[10], *ptr;

main()
{
//reading the members of array of structures using pointer
for(ptr=b; ptr<b+10; ptr++)
scanf(“%s %d \n”, ptr->name, &ptr->price);
ptr = b;
//displaying the array of structures using pointer
while(ptr<b+10)
{
printf(“%s %d \n”, ptr->name, ptr->price);
ptr++;
}
}
Trouble with Pointers
•Since pointer holds address of memory location, it must never be used without
proper initialization.

• Not de- referencing a pointer when required.

• An uninitialized pointer does not know the memory location it is pointing to.
• A pointer cannot track boundaries of an array.
• Comparing pointers that point to different objects.
References
• Slideshare
• https://www.tutorialspoint.com/cprogramming/c_pointers.htm
• https://dyclassroom.com/c/c-pointers-and-strings
• https://www.studytonight.com/c/pointer-with-function-in-c.php
• https://www.studytonight.com/c/pointers-to-structure-in-c.php
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy