S23 - 1 - Pointers
S23 - 1 - Pointers
* 1
Objectives
To learn and appreciate the following concepts
* 2
Session outcome
At the end of session one will be able to understand
* 3
Pointers- recap
int Quantity; //defines variable Quantity of type int
int* p; //defines p as a pointer to int
p = &Quantity; //assigns address of variable Quantity to pointer p
Now…
Quantity = 50;//assigns 50 to Quantity
*p = 50; //assigns 50 to Quantity
* 4
Pointer expressions
• Pointers can be used in most valid C expressions. However, some special
rules apply.
* 5
Pointer Expressions - Example
• Eg: int a=10, b=20,c,d=10;
int *p1 = &a, *p2 = &b;
Expression a b c
c= *p1**p2; OR *p1 * *p2 10 20 200
OR (*p1) * (*p2)
c= c + *p1; 10 20 210
* 6
Operations on Pointer Variables
• Assignment – the value of one pointer variable can be assigned to
another pointer variable of the same type
• Relational operations - two pointer variables of the same type can be
compared for equality, and so on
• Some limited arithmetic operations
• integer values can be added to and subtracted from a pointer variable
• value of one pointer variable can be subtracted from another pointer variable
• Shorthand Increment and Decrement Operators
* 7
Allowed Pointer Operations - Example
• int a = 10, b = 20, *p1, *p2, *p3, *p4; Assume an
integer
• p1 = &a; //assume address of a = 2004 occupies 4
bytes
• p2 = &b; //assume address of b = 1008
Pointer Operations Example expression Result
Addition of integers from p3 = p1 + 2 value of p3 = 2004 + 4*2 = 2012
pointers
Subtraction of integers from p4 = p2 – 2 value of p4 = 1008-4*2 = 1000
pointers
Subtraction of one pointer c = p3– p1 Value of c = 2012– 2004= 2
from another
Pointer Increment p1++ Value of p1 = 2008
Pointer Decrement --p1 Value of p1 = 2004
* 8
Allowed Pointer Operations - Example
if (p1<p2)
printf(“p1 points to lower memory than p2”);
if (p1==p2)
printf(“ p1 and p2 points to same location”);
if (p1!=p2)
printf(“ p1 and p2 NOT pointing to same location”);
* 9
Invalid Operations:
▪Pointers are not used in division and multiplication.
p1/*p2;
p1*p2;
p1/3; are not allowed.
* 10
Program to exchange two values
#include<stdio.h>
int main()
{
* 12