Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 41

Pointers

05/23/2024 CSE 1001 Department of CSE 1


Pointers - Concept
• Consider the following statement

int Quantity =50;

- Compiler will allocate a memory location for Quantity and places the
value in that location. Suppose the address of that location is 5000, then

05/23/2024 CSE 1001 Department of CSE 2


Pointer
-A memory location or a variable which stores the address of
another variable in memory

05/23/2024 CSE 1001 Department of CSE 3


Declaring and initializing pointers
Syntax:
data_type * pt_name;

This tells the compiler 3 things about the pt_name:

 The asterisk(*) tells the variable pt_name is a pointer


variable.
 pt_name needs a memory location.
 pt_name points to a variable of type data_ type

05/23/2024 CSE 1001 Department of CSE 4


Declaring and initializing pointers
Example:
int *p; //declares a variable p as a pointer variable
that points to an integer data type.

float *x; //declares x as a pointer to floating point


variable.

• Once a pointer variable has been declared, it can be made to point to a variable
using an assignment statement :

int quantity = 10;


p = &quantity; // p now contains the address of quantity. This is known as
pointer initialization.

05/23/2024 CSE 1001 Department of CSE 5


Accessing the address of a variable
int Quantity=50 ;
• To assign the address 5000 (the
location of quantity) to a variable
p, we can write:

int *p = &Quantity ;
Such variables that hold memory
addresses are called
Pointer Variables.

05/23/2024 CSE 1001 Department of CSE 6


Program to illustrate the address of operator
#include <stdio.h>
Output:
int main()
{ 0x29feec
int var1 = 11; 0x29fee8
int var2 = 22; 0x29fee4
int var3 = 33;

//print the addresses of these variables


printf(“%x”,&var1);
printf(“%x”,&var2);
printf(“%x”,&var3);
return 0;
05/23/2024 CSE 1001 Department of CSE 7
}
Pointers Concept

The Address-of Operator &

• To find the address occupied by a variable

05/23/2024 CSE 1001 Department of CSE 8


Summary till now …
int v; //defines variable v of type int
int* p; //defines p as a pointer to int

p = &v; //assigns address of variable v to pointer p

Now…
v = 3; //assigns 3 to v

05/23/2024 CSE 1001 Department of CSE 9


To be taken care …
 Before a pointer is initialized, it should not be used.
 We must ensure that the pointer variables always point to the corresponding
type of data.
 Assigning an absolute address to a pointer variable is prohibited. i.e p=5000
 A pointer variable can be initialized in its declaration itself.
Example:
int x, *p=&x; //declares x as an integer
variable and then initializes
p to the address of x.

05/23/2024 CSE 1001 Department of CSE 10


To be taken care …
The statement

int *p = & x, x; not valid.

i.e target variable ‘x’ must be declared first.

05/23/2024 CSE 1001 Department of CSE 11


Accessing variable through a pointer
• A variable’s value can be accessed by its pointer using
unary operator *(asterisk) known as indirection
operator.

Consider the following statements:


int quantity, *p, n; // 2 int variables & 1 integer pointer
quantity =50; // assigns value 50 to quantity
p=&quantity; // assigns the address of quantity to p
n=*p; // contains the indirection operator *

* Operator - value at address operator


05/23/2024 CSE 1001 Department of CSE 12
Example – Accessing variable through a pointer
#include <stdio.h>
Output :
int main() 11
{ 22
int var1 = 11; //two integer variables
int var2 = 22;
int *ptr; //pointer to integer

ptr = &var1; //pointer points to var1


printf(“%d”,*ptr); //print contents of pointer (11)

ptr = &var2; //pointer points to var2


printf(“%d”,*ptr); //print contents of pointer (22)

return 0;
}
05/23/2024 CSE 1001 Department of CSE 13
Example - Accessing via pointers.
#include <stdio.h>
int main()
{
int var1, var2; //two integer variables
int *ptr; //pointer to integers
ptr = &var1; //set pointer to address of
*ptr = 37; //same as var1=37
( Dereferencing)
var2 = *ptr; //same as var2=var1
printf(“%d”, var2); //verify var2 is 37
return 0;
}
05/23/2024 CSE 1001 Department of CSE 14
Reference and dereference
operators
 & is the ‘reference’ operator and can be read as
"address of"

 * is the ‘dereference’ operator and can be read as


“value at address” or "value pointed by"

05/23/2024 CSE 1001 Department of CSE 15


Example- understanding pointers
#include <stdio.h>

int main()

int firstvalue = 5, secondvalue = 15;


Output :
int * p1, * p2; firstvalue is 10
p1 = &firstvalue; // p1 = address of firstvalue secondvalue is 20
p2 = &secondvalue; // p2 = address of secondvalue

*p1 = 10; // value pointed by p1 = 10

*p2 = *p1; // value pointed by p2 = value pointed by p1

p1 = p2; // p1 = p2 (value of pointer is copied)

*p1 = 20; // value pointed by p1 = 20

printf(“%dfirstvalue is\n ",firstvalue);

printf( “%dsecondvalue is “,secondvalue);

return 0;

05/23/2024 CSE 1001 Department of CSE 16


Pointer expressions
• Pointers can be used in most valid C expressions.
However, some special rules apply.

• You may need to surround some parts of a pointer


expression with parentheses in order to ensure that the
outcome is what you desire.

• As with any variable, a pointer may be used on the right


side of an assignment operator to assign its value to
another pointer.

05/23/2024 CSE 1001 Department of CSE 17


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

c=5 * - *p2 / *p1; 10 20 -10


OR ( 5 * (- (*p2)))/(*p1)
//space between / and * is required
*p2 =*p2 +10; 10 30

05/23/2024 CSE 1001 Department of CSE 18


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

05/23/2024 CSE 1001 Department of CSE 19


Allowed Pointer Operations - Example
Assume an
• int a = 10, b = 20, *p1, *p2, *p3, *p4; integer
occupies 4
• p1 = &a; //assume address of a = 2004 bytes

• p2 = &b; //assume address of b = 1008


Pointer Operations Example expression Result
Addition of integers p3 = p1 + 2 value of p3 = 2004 + 4*2 =
from pointers 2012
Subtraction of integers p4 = p2 – 2 value of p4 = 1008-4*2 =
from pointers 1000
Subtraction of one c = p3– p1 Value of c = 2012– 2004= 2
pointer from another
Pointer Increment p1++ Value of p1 = 2008
Pointer Decrement --p1 Value of p1 = 2004

05/23/2024 CSE 1001 Department of CSE 20


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”);

05/23/2024 CSE 1001 Department of CSE 21


Invalid Operations:
 Pointers are not used in division and
multiplication.
p1/p2;
p1*p2;
p1/3; are not allowed.

 Two pointers can not be added.


p1 + p2 is illegal.

05/23/2024 CSE 1001 Department of CSE 22


Program to exchange two values
#include<stdio.h>
int main()
{

int x, y, t, *a, *b;


a=&x; b=&y;
printf("Enter the values of a and b: \n");
scanf("%d %d", a, b); // equivalent to scanf(“%d %d”, &x, &y);
t=*a;
*a=*b;
*b=t;
Enter the values of a and b:
printf("x = %d \n", x);
10 5
printf("y = %d", y); x= 5
y = 10
return 0;
}
05/23/2024 CSE 1001 Department of CSE 23
BASIC OPERATIONS ON
Pointers AND
POINTERS TO ARRAYS

05/23/2024 CSE 1001 Department of CSE 24


Pointers and arrays
 When an array is declared, the compiler allocates a
base address and sufficient amount of storage to
contain all the elements of the array in contiguous
memory locations.

 The base address is the location of the first element


(index 0) of the array.

 The compiler also defines the array name as a


constant pointer to the first element.

05/23/2024 CSE 1001 Department of CSE 25


Pointers and arrays
An array x is declared as follows and assume the
base address of x is 1000.
int x[5] ={ 1,2,3,4,5};
Array name x, is a constant pointer, pointing to
the first element x[0] .
Value of x is 1000 (Base Address), the location of
x[0]. i.e. x = &x[0] = 1000 (in the example
below)

05/23/2024 CSE 1001 Department of CSE 26


Array accessing using Pointers
•An integer pointer variable p, can be made to point to an array
as follows:
int x[5] ={ 1,2,3,4,5};
int *p;
p = x; OR p = &x[0];

Following statement is Invalid:


p = &x ; //Invalid

•Successive array elements can be accessed by writing:


printf(“%d”, *p); p++;
or
printf(“%d”, *(p+i)); i++;
05/23/2024 CSE 1001 Department of CSE 27
Pointers and arrays
• The relationship between p and x is shown below:

p= &x[0]; (=1000) BASE ADDRESS


p+1=>&x[1] (=1004)
p+2=>&x[2] (=1008)
p+3=>&x[3] (=1012)
p+4=>&x[4] (=1016)

•Address of an element of x is given by:


Address of x[i] = base address + i * scale factor of (int)
Address of x[3]= 1000 +(3*4) = 1012

05/23/2024 CSE 1001 Department of CSE 28


Array accessing using array name
as pointer
#include <stdio.h>
- Example
int main()
{

int arr[5] = { 31, 54, 77, 52, 93 };


Int j;

for( j=0; j<5; j++) //for each element,


printf(“%d ”, *(arr+j)); //print value

return 0;
05/23/2024 } CSE 1001 Department of CSE 29
Array accessing using Pointers - Example
// array accessed with pointer
#include <stdio.h>

int main()
{

int arr[5] = { 31, 54, 77, 52, 93 };


int* ptr; //pointer to arr
ptr = arr; //points to arr

for(int j=0; j<5; j++) //for each element,


printf("%d ", *ptr++);

return 0;
}

05/23/2024 “ptr” is a pointer which can be used


CSE 1001 to access
Department of CSE the elements. 30
Sum of all elements stored in an array
#include <stdio.h>
int main()
{
int *p, sum=0, i=0;
int x[5] ={5, 9, 6,3,7};
p=x;
while(i<5)
{
sum+=*p;
i++;
p++;
}
printf("sum of elements = %d“, sum);
return 0;
}
05/23/2024 CSE 1001 Department of CSE 31
Pointers & Character strings
//length of the string
#include <stdio.h>
int main()
{
char name[15];
char *cptr=name;
printf("Enter some word to find its length: \n“);
scanf(“%s”, name);
while(*cptr!= '\0')
cptr++;
printf("length= %d"cptr-name);
return 0;
05/23/2024 } CSE 1001 Department of CSE 32
Pointers & Character strings
 The statements
char name[10];
char *cptr =name;
declares cptr as a pointer to a character array and
assigns address of the first character of name as the
initial value.
The statement while(*cptr!=‘\0’)
is true until the end of the string is reached.
When the while loop is terminated, the pointer cptr
holds the address of the null character [‘\0’].
The statement length = cptr – name; gives the
length of the string name.
05/23/2024 CSE 1001 Department of CSE 33
Pointers & Character strings
• A constant character string always represents a
pointer to that string.
• The following statements are valid.
char *name;
name =“Delhi”;
These statements will declare name as a pointer
to character array and assign to name the
constant character string “Delhi”.

05/23/2024 CSE 1001 Department of CSE 34


Pointers and 2D arrays
int a[][2]={ {12, 22},
{33, 44} };
int (*p)[2];
p=a; // initialization

Element in 2d represented as

*(*(a+i)+j)
or
*(*(p+i)+j)

05/23/2024 CSE 1001 Department of CSE 35


Pointers and 2D arrays
// 2D array accessed with pointer
#include <stdio.h>
int main()
{

int i, j, (*p)[2], a[][2] = {{12, 22}, {33, 44} };

p=a;

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%d \t“, *(*(p+i)+j));
printf("\n“);
}

return 0;
05/23/2024 CSE 1001 Department of CSE 36
}
Array of pointers
 We can use pointers to handle a table of strings.
char name[3][25];
name is a table containing 3 names, each with a
maximum length of 25 characters (including ‘\0’)

 Total storage requirement for name is 75 bytes.


But rarely all the individual strings will be equal in
lengths.

 We can use a pointer to a string of varying length as

char *name[3] = { “New Zealand”, “Austrailia”, “India” };

05/23/2024 CSE 1001 Department of CSE 37


Array of pointers
So, char *name[3] = { “New Zealand “,
“Australia”,
“India”};
Declares name to be an array of 3 pointers to
characters, each pointer pointing to a particular
name.
name[0]  New Zealand
name[1] Australia
name[2] India
This declaration allocates 28 bytes.
05/23/2024 CSE 1001 Department of CSE 38
Array of pointers
The following statement would print out all the 3
names.
for(i=0; i<=2;i++)
printf(“%s”,name[i]);
or printf(“%s”, *(name + i));

To access the jth character in the ith name, we


may write as
*(name[i] +j)

The character array with rows of varying lengths are


called ragged arrays and are better handled by
pointers.
05/23/2024 CSE 1001 Department of CSE 39
Pointer to Void Type
• The void pointer in C is a pointer which is not associated with
any data types.
• It points to some data location in the storage means points to
the address of variables. It is also called general purpose
pointer.
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}
05/23/2024 CSE 1001 Department of CSE 40
Pointer to Void Type
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}

OUTPUT:
Integer variable is = 7
Float variable is = 7.600000

05/23/2024 CSE 1001 Department of CSE 41

You might also like