0% found this document useful (0 votes)
5 views57 pages

Pointer

Pointers are variables that store the memory addresses of other variables, allowing for efficient data handling and manipulation in programming. They enable access to variables outside their scope, facilitate data exchange between functions, and can simplify code complexity. Proper declaration and usage of pointers are crucial, as they must point to the correct data type and can be used in expressions to manipulate memory addresses.

Uploaded by

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

Pointer

Pointers are variables that store the memory addresses of other variables, allowing for efficient data handling and manipulation in programming. They enable access to variables outside their scope, facilitate data exchange between functions, and can simplify code complexity. Proper declaration and usage of pointers are crucial, as they must point to the correct data type and can be used in expressions to manipulate memory addresses.

Uploaded by

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

Pointers

1
Introduction

• A pointer is a variable that represents the location (rather than


the value) of a data item.
• They have a number of useful applications.
– Enables us to access a variable that is defined outside the
function.
– Can be used to pass information back and forth between a
function and its reference point.
– More efficient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.

2
Basic Concept

• In memory, every stored data item occupies one or more


contiguous memory cells.
– The number of memory cells required to store a data item
depends on its type (char, int, double, etc.).

• Whenever we declare a variable, the system allocates


memory location(s) to hold the value of the variable.
– Since every byte in memory has a unique address, this
location will also have its own (unique) address.

3
Contd.

• Consider the statement


int xyz = 50;

– This statement instructs the compiler to allocate a location for


the integer variable xyz, and put the value 50 in that
location.

– Suppose that the address location chosen is 1380.

xyz -> variable


50 -> value
1380 -> address

4
Contd.

• During execution of the program, the system always


associates the name xyz with the address 1380.

– The value 50 can be accessed by using either


the name
xyz or the address 1380.
• Since memory addresses are simply numbers, they can be
assigned to some variables which can be stored in
memory.
– Such variables that hold memory addresses are called
pointers.
– Since a pointer is a variable, its value is also stored in
some memory location.
5
Contd.

• Suppose we assign the address of xyz to a variable


p.
– p is said to point to the variable xyz.

Variable Value Address


xyz 50 1380 p = &xyz;
p 1380 2545

6
Address vs. Value

• Each memory cell has an address associated with it.


• Each cell also stores some value.

• Don’t confuse the address referring to a memory location with


the value stored in that location.

101 102 103 104 105 ...


... 23 42 ...

7
Values vs Locations

• Variables name memory locations, which hold values.

value
1024: 32
x
address name New Type : Pointer

8
Pointers

• A pointer is just a C variable whose value is the address of


another variable!

• After declaring a pointer:

int *ptr;
ptr doesn’t actually point to anything yet. We can
either:
– make it point to something that already exists, or
– allocate room in memory for something new that it will
point to… (next time)

9
Pointer

int x; pointer to int Pointers Abstractly

int  xp ; 1024: 32 int x;


x
int * p;
xp = &x ; 1024
xp p=&x;
...
address of x (x == *p)
True (p == &x)
xp = 0; /* Assign 0 to x */
xp = xp + 1; /* Add 1 to x */ True

10
Pointers

• Declaring a pointer just allocates space to hold the pointer –


it does not allocate something to be pointed to!

• Local variables in C are not initialized, they may contain


anything.

11
Pointer Usage Example

0xffff ffff Memory and Pointers:

0xcafe 0000

0xbeef 0000

0x0000 0004
0x0000 0000

12
Pointer Usage Example

0xffff ffff Memory and Pointers:


int *p, v;

v: 0xXXXXXXXX 0xcafe 0000

p: 0xXXXXXXXX 0xbeef 0000

0x0000 0004
0x0000 0000

13
Pointer Usage Example

0xffff ffff Memory and Pointers:


int *p, v;
p = &v;
v: 0xXXXXXXXX 0xcafe 0000

p: 0xcafe 0000 0xbeef 0000

0x0000 0004
0x0000 0000

14
Pointer Usage Example

0xffff ffff Memory and Pointers:


int *p, v;
p = &v;
v: 0x0000 0017 0xcafe 0000 v = 0x17;

p: 0xcafe 0000 0xbeef 0000

0x0000 0004
0x0000 0000

15
Pointer Usage Example

0xffff ffff Memory and Pointers:


int *p, v;
p = &v;
v: 0x0000 001b 0xcafe 0000 v = 0x17;
*p = *p + 4;
0xcafe 0000
p: 0xbeef 0000 V = *p + 4

0x0000 0004
0x0000 0000

16
Accessing the Address of a Variable

• The address of a variable can be determined using the ‘&’


operator.
– The operator ‘&’ immediately preceding a variable returns
the address of the variable.

• Example:
p = &xyz;
– The address of xyz (1380) is assigned to
p.
• The ‘&’ operator can be used only with a simple variable or an
array element.
&distance
&x[0]
&x[i-2]

17
Contd.

• Following usages are illegal:


&235
• Pointing at constant.

int arr[20];
:
&arr;
• Pointing at array
name.

&(a+b)
• Pointing at
expression.

18
Example

#include <stdio.h>
main()
{
int
a; float
double
b, c;
char d;
ch;
a = 10; b = 2.5; c = 12.36; d = ch = ‘A’;
12345.66;
printf (“%d is stored in location %u \n”, a, &a) ;
printf (“%f is stored in location %u \n”, b, &b) ;
printf (“%f is stored in location %u \n”, c, &c) ;
printf
printf (“%ld
(“%c isisstored
storedin
inlocation
location%u
%u\n”,
\n”, d,
ch, &d) ;;
&ch)
}

19
Output:

10 is stored in location 3221224908


2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891

20
Pointer Declarations

• Pointer variables must be declared before we use them.

• General form:
data_type *pointer_name;

• Three things are specified in the above declaration:


• The asterisk (*) tells that the variable pointer_name
is a pointer variable.
• pointer_name needs a memory location.
• pointer_name points to a variable of type data_type.

21
Contd.
• Example:
int *count;
float *speed;

• Once a pointer variable has been declared, it can be made to point


to a variable using an assignment statement like:
int *p, xyz;
:
p = &xyz;
– This is called pointer initialization.

22
Things to Remember

• Pointer variables must always point to a data item of the same


type.

float
x;
int *p;  will result in erroneous output
:
p = &x;

• Assigning an absolute address to a pointer variable is


prohibited.

int *count;
:
count = 1268;

23
Accessing a Variable Through its Pointer

• Once a pointer has been assigned the address of a variable, the


value of the variable can be accessed using the indirection
operator (*).

int a,
b;
Equivalent to b = a;
int *p;
:
p = &a;
b =
*p;

24
Example 1

#include <stdio.h>
main()
{ Equivalent
int a,
b;
int c =
5;
int *p;
(c + 5) ;

p
a = &c;= 4 *
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b);
} a=40 b=40

25
Example 2
#include <stdio.h>
main()
{
int x, y;
int *ptr;

x = 10 ;
ptr = &x ;
y = *ptr ;
printf (“%d is stored in location %u \n”, x, &x) ;
printf (“%d is stored in location %u \n”, *&x, &x) ;
printf (“%d is stored in location %u \n”, *ptr, ptr);
printf (“%d is stored in location %u \n”, y,
&*ptr) ;
printf (“%u is stored in location %u \n”, ptr, &ptr) ;
printf (“%d is stored in location %u \n”, y, &y) ;

*ptr = 25;
printf (“\nNow x = %d \n”, x);
} 26
Address of x: 3221224908
Address of y: 3221224904
Address of ptr: 3221224900

Output:

10 is stored in location 3221224908


10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
3221224908 is stored in location 3221224900
10 is stored in location 3221224904

Now x = 25
27
Pointer Expressions

• Like other variables, pointer variables can be used in expressions.

• If p1 and p2 are two pointers, the following statements are valid:


sum = *p1 + *p2;
prod = *p1 * *p2;
prod = (*p1) * (*p2);
*p1 can appear
*p1 = *p1 + 2; on the left hand
x = *p1 / *p2 + 5; side

28
Contd.

• What are allowed in C?


– Add an integer to a pointer.
– Subtract an integer from a pointer.
– Subtract one pointer from another (related).
• If p1 and p2 are both pointers to the same array, then
p2– p1 gives the number of elements between
p1 and p2.

29
Contd.

• What are not allowed?


– Add two pointers.
p1 = p1 + p2;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5;
p1 = p1 – p2 * 10;

30
Scale Factor

• We have seen that an integer value can be added to or


subtracted from a pointer variable.

int *p1, *p2;


int i, j;
:
p1 = p1 + 1;
p2 = p1 + j;
p2++;
p2 = p2 – (i
+ j);
– In reality, it is not the integer value which is added/subtracted,
but rather the scale factor times the value.
31
Contd.

Data Type Scale Factor


char 1
int 4
float 4
double 8

– If p1 is an integer pointer, then


p1++
will increment the value of p1 by 4.

32
• Note:
– The exact scale factor may vary from one machine to another.
– Can be found out using the sizeof function.
– Syntax:
sizeof (data_type)

33
Example: to find the scale factors

#include <stdio.h>
main()
{
printf (“No. of bytes occupied by int is %d \n”, sizeof(int));
printf (“No. of bytes occupied by float is %d \n”, sizeof(float));
printf (“No. of bytes occupied by double is %d \n”, sizeof(double));
printf (“No. of bytes occupied by char is %d \n”, sizeof(char));
}

Output:

Number of bytes occupied by int is 4


Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1

34
Passing Pointers to a Function

• Pointers are often passed to a function as arguments.


– Allows data items within the calling program to be
accessed by the function, altered, and then returned to the
calling program in altered form.
–Called call-by-reference (or by address or by location).
• Normally, arguments are passed to a function by value.
– The data items are copied to the function.
– Changes are not reflected in the calling program.

35
Example: passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20;
swap (a, b); Output
printf (“\n a=%d, b=%d”, a, b);
} a=5, b=20

void swap (int x, int y)


{
int t;
t = x;
x = y;
y = t;
}

36
Example: passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20;
swap (&a, &b); Output
printf (“\n a=%d, b=%d”, a, b); a=20, b=5
}

void swap (int *x, int *y)


{
int t;
t = *x;
*x = *y;
*y = t;
}

37
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.

38
Example

• Consider the declaration:


int x[5] = {1, 2, 3, 4, 5};
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516

39
Contd.

Both x and &x[0] have the value 2500.

p = x; and p = &x[0]; are equivalent.


– We can access successive values of x by using p++ or p--
to move from one element to another.

• Relationship between p and x:


p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
*(p+i) gives the
value of
x[i] 40
Example: function to find average

#include <stdio.h> float avg (array, size)


main() int array[], size;
{ {
int x[100], k, int *p, i , sum =
n; 0;

scanf (“%d”, &n); p = array;

for (k=0; k<n; k++) for (i=0; i<size; i++)


scanf (“%d”, sum = sum + *(p+i);
printf
&x[k]);
(“\nAverage is %f”,
avg (x, n)); return ((float) sum /
} size);
}

41
Pointers and Structures

• You may recall that the name of an array stands for the
address of its zero-th element.
– Also true for the names of arrays of structure variables.

Consider the declaration:
struct stud {
int roll;
char
dept_code[25];
float cgpa;
} class[100], *ptr ;

42
– The name class represents the address of the zero-
th element of the structure array.
– ptr is a pointer to data objects of the type struct
stud.
• The assignment
ptr = class;
will assign the address of class[0] to
ptr.
• When the pointer ptr is incremented by one (ptr+
+) :
– The value of ptr is actually increased by sizeof(stud).
– It is made to point to the next record.

43
• Once ptr points to a structure variable, the
members can be accessed as:
ptr –> roll;
ptr –> dept_code;
ptr –> cgpa;

– The symbol “–>” is called the arrow operator.

44
A Warning

• When using structure pointers, we should take care


of operator precedence.
– Member operator “.” has higher precedence than “*”.
ptr –> roll and (*ptr).roll mean the same thing.
*ptr.roll will lead to error.

– The operator “–>” enjoys the highest priority


among operators.
++ptr –> roll will increment
roll, not ptr. (++ptr) –> roll
will do the
intended thing.

45
Structures and Functions

• A structure can be passed as argument to a function.


• A function can also return a structure.
• The process shall be illustrated with the help of an
example.
– A function to add two complex numbers.

46
Example: complex number addition
#include <stdio.h> struct complex add (x, y)
struct complex { struct complex x, y;
f {
l
struct complex t;
o
a
t t.re = x.re + y.re ;
main() t.im = x.im +
{ r y.im ; return (t) ;
struct complexe a, b, c; }
;
scanf (“%f %f”, &a.re, &a.im);
f
scanf (“%f %f”, &b.re, &b.im);
l
c add (a, b)o ;
(“\n %fa%f”, c,re, c.im);
} = t
printf
i
m
;
}; 47
Example: Alternative way using pointers

#include <stdio.h>
struct complex {
f
l void add (x, y, t)
o
struct complex *x, *y, *t;
a
t {
main() t->re = x->re + y->re;
{ r t->im = x->im + y-
struct complex e a, b, c; } >im;
;
scanf (“%f %f”, &a.re, &a.im);
f
(“%f %f”, &b.re, &b.im);
l
scanf
add (&a, &b, &c) o;
printf (“\n %f %f”,
a c,re, c.im);
} t

i
m
;
}; 48
Linked List :: Basic Concepts

• A list refers to a set of items organized sequentially.


– An array is an example of a list.
• The array index is used for accessing and manipulation of array
elements.
– Problems with array:
• The array size has to be specified at the beginning.
• Deleting an element or inserting an element may require shifting of
elements.

49
Contd.

• A completely different way to represent a list:


– Make each item in the list part of a structure.
– The structure also contains a pointer or link to the structure
containing the next item.
– This type of list is called a linked list.

Structure 1 Structure 2 Structure 3

item item item

50
Contd.
• Each structure of the list is called a node, and
consists of two fields:
– One containing the item.
– The other containing the address of the next item in the
list.
• The data items comprising a linked list need not
be contiguous in memory.
– They are ordered by logical links that are stored as part
of the data in the structure itself.
– The link is a pointer to another structure of the same
type.

51
Contd.

• Such a structure can be represented as:


struct node
{
int item;
struct node *next;
}
node
item

• next

Such structures which contain a member field


pointing to the same structure type are called
self-referential structures.
52
Contd.

• In general, a node may be represented as follows:

struct node_name
{
type

member1; type
member2;
………
struct
node_name
*next;
}

53
Illustration

• Consider the structure:


struct stud
{
int

roll; char
name[30]; int

age;
struct stud
*next;
}
• Also assume that the list consists of three nodes n1, n2
and n3.
struct stud n1, n2, n3;
54
Contd.

• To create the links between nodes, we can write:


n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ; /* No more nodes follow */
• Now the list looks like:

roll
name
age
next

n1 n2 n3
55
Example

#include <stdio.h>
struct stud
{
int roll;
char
name[30]; int
age;
struct
stud
main()*next;
{ }
struct stud n1, n2, n3;
*p;
struct stud
scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age);
scanf (“%d %s %d”, &n2.roll, n2.name,
&n2.age); scanf (“%d %s %d”, &n3.roll,
n3.name, &n3.age);
56
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;

/* Now traverse the list and print the elements */

p = n1 ; /* point to 1st
element */ while (p !=
NULL)
{
printf (“\n %d %s %d”,
p->roll, p->name, p->age);
p = p->next;
}
}

57

You might also like