Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
49 views61 pages

Unit II Pointers

This document provides an introduction to pointers in 3 sections: 1. It defines pointers as variables that store memory addresses rather than values, and outlines some of their applications. 2. It explains how variables are stored in memory with unique addresses, and how pointers can be used to point to these memory locations. 3. It covers pointer declarations and initialization, accessing variables through pointers using the dereference operator, and basic pointer arithmetic operations.

Uploaded by

Manikyaraju
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)
49 views61 pages

Unit II Pointers

This document provides an introduction to pointers in 3 sections: 1. It defines pointers as variables that store memory addresses rather than values, and outlines some of their applications. 2. It explains how variables are stored in memory with unique addresses, and how pointers can be used to point to these memory locations. 3. It covers pointer declarations and initialization, accessing variables through pointers using the dereference operator, and basic pointer arithmetic operations.

Uploaded by

Manikyaraju
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/ 61

UNIT II

Pointers

* Programming and Problem Solving II 1


Syllabus

Pointers: Introduction to Pointers, Pointer Arithmetic,


Pointers and Arrays, Pointers to Structures, Pointers and
Strings, Function - Call by Reference, Pointers to Pointers,
Dynamic-Memory-Allocation.

* Programming and Problem Solving II 2


Introduction to Pointers

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

* Programming and Problem Solving II 3


Introduction to Pointers

• Within the computer 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.

* Programming and Problem Solving II 4


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

* Programming and Problem Solving II 5


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.
* Programming and Problem Solving II 6
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

2545 1380 1380 50


p xyz
* Programming and Problem Solving II 7
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]
* Programming and Problem Solving II 8
Contd.

• Following usages are illegal:


&235
• Pointing at constant.

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

&(a+b)
• Pointing at expression.

* Programming and Problem Solving II 9


Example

#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;

a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = ‘A’;


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 (“%ld is stored in location %u \n”, d, &d) ;
printf (“%c is stored in location %u \n”, ch, &ch) ;
}

* Programming and Problem Solving II 10


Output:

10 is stored in location 3221224908 a


2.500000 is stored in location 3221224904 b
12.360000 is stored in location 3221224900 c
12345.660000 is stored in location 3221224892 d
A is stored in location 3221224891 ch

Incidentally variables a,b,c,d and ch are allocated


to contiguous memory locations.

* Programming and Problem Solving II 11


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:
1. The asterisk (*) tells that the variable pointer_name is a
pointer variable.
2. pointer_name needs a memory location.
3. pointer_name points to a variable of type data_type.

* Programming and Problem Solving II 12


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.

* Programming and Problem Solving II 13


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;

* Programming and Problem Solving II 14


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;
int *p;
: Equivalent to b=a
p = &a;
b = *p;

* Programming and Problem Solving II 15


Example 1

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

a = 4 * (c + 5) ;

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

* Programming and Problem Solving II 16


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

x = 10 ;
ptr=&x;
ptr = &x ; &x⬄&*ptr
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);
}
* Programming and Problem Solving II 17
Output: Address of x: 3221224908
Address of y: 3221224904

10 is stored in location 3221224908


Address of ptr: 3221224900
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

* Programming and Problem Solving II 18


Pointer Arithmetic

• 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 = *p1 + 2;
x = *p1 / *p2 + 5 ;

* Programming and Problem Solving II 19


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, them
p2–p1 gives the number of elements between p1 and p2.
• What are not allowed?
– Add two pointers.
p1 = p1 + p2 ;
– Multiply / divide a pointer in an expression.
p1 = p2 / 5 ;
p1 = p1 – p2 * 10 ;

* Programming and Problem Solving II 20


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.

* Programming and Problem Solving II 21


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.

* Programming and Problem Solving II 22


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.

* Programming and Problem Solving II 23


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

* Programming and Problem Solving II 24


Contd.

x ⬄ &x[0] ⬄ 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+i) gives the
p+3 = &x[3] = 2512 value of x[i]
p+4 = &x[4] = 2516

* Programming and Problem Solving II 25


Example: Pointers and Arrays

* Programming and Problem Solving II 26


Example: function to find average
int *array
#include <stdio.h> float avg (int array[ ],int size)
main() {
{ int *p, i , sum = 0;
int x[100], k, n ;
p = array ; p[i]
scanf (“%d”, &n) ;
for (i=0; i<size; i++)
for (k=0; k<n; k++) sum = sum + *(p+i);
scanf (“%d”, &x[k]) ;
return ((float) sum / size);
printf (“\nAverage is %f”, }
avg (x, n));
}

* Programming and Problem Solving II 27


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 ;

* Programming and Problem Solving II 28


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

* Programming and Problem Solving II 29


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

* Programming and Problem Solving II 30


Example
#include <stdio.h> swap_ref(_COMPLEX *a, _COMPLEX *b)
{
typedef struct { _COMPLEX tmp;
float real; tmp=*a;
float imag; *a=*b;
} _COMPLEX; *b=tmp;
}
main()
print(_COMPLEX *a)
{
{
_COMPLEX x={10.0,3.0}, y={-20.0,4.0};
printf("(%f,%f)\n",a->real,a->imag);
}
(10.000000,3.000000) print(&x); print(&y);
(-20.000000,4.000000) swap_ref(&x,&y);
(-20.000000,4.000000) print(&x); print(&y);
}
(10.000000,3.000000) Programming and Problem
* Solving II 31
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.

* Programming and Problem Solving II 32


Example: Pointers to Structures
struct student{
int sno;
char sname[30];
float marks;
};
main ( )
{
struct student s;
struct student *st;
st = &s;
printf("enter sno, sname, marks :");
scanf ("%d%s%f", st->sno, st->sname, st->marks);
printf ("details of the student are\n");
printf ("Number = %d\n", st ->sno); s.sno
printf ("name = %s\n", st->sname); s.sname
printf ("marks =%f", st->marks); s.marks
getch ( );
}
* Programming and Problem Solving II 33
Example: pointers to structures
#include <stdio.h> void add (x, y, t)
struct complex { struct complex *x, *y, *t;
float re; {
float im; t->re = x->re + y->re ;
}; t->im = x->im + y->im ;
}
main()
{
struct complex a, b, c;
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
add (&a, &b, &c) ;
printf (“\n %f %f”, c,re, c.im);
}

* Programming and Problem Solving II 34


Pointer and Strings
String is a sequence of characters which we save in an
array. And in C programming language the \0 null
character marks the end of a string.

* Programming and Problem Solving II 35


Pointer and Strings
Creating a pointer for the string
• The variable name of the string str holds the address of
the first element of the array i.e., it points at the starting
memory address.
• So, we can create a character pointer ptr and store the
address of the string str variable in it.

• Eg:
char *ptr = str; //assigning address of the str to pointer ptr.

* Programming and Problem Solving II 36


Pointer and Strings
We can represent the character pointer variable ptr as
follows.

The pointer variable ptr is allocated memory address 8000 and it holds the address of the string
variable
* str i.e., 1000. Programming and Problem Solving II 37
Pointer and Strings: Example

* Programming and Problem Solving II 38


Pointer and Strings: Example

# include<stdio.h>
int main(void) {
// pointer variable to store string
char *strPtr = "Hello";
// temporary pointer variable
char *t = strPtr; // print the string
while(*t != '\0')
{ printf("%c", *t); // move the t pointer to the next memory
location
t++;
}
return 0; }

* Programming and Problem Solving II 39


Pointer and Strings: Example
void strcpy(char *s, char
int strcmp(char *s, char
int strlen(char *s) *t)
*t)
{ {
{
int n; int i = 0;
int i;
for(n = 0; *s != ‘\0’; while((s[i] = t[i]) !=
for(i=0;s[i] = =
s++) ‘\0’)
t[i];i++)
n++; i++;
if(s[i] = = ‘\0’)
return n; void
} strcpy(char *s, char
return 0; *t)
} int strcmp(char – t[i];
return s[i]*s, char *t) {
{ } while((*s = *t) != ‘\0’)
for( ; *s = = *t; s++, {
t++)
s++; t++;
if(*s = = ‘\0’) return
0; }
}
return *s - *t; void strcpy(char *s, char *t)
} {
* Programming and Problem Solving II while((*s++ = *t++) != 40
‘\0’);
Passing Pointers to a Function- Call by reference
• 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.

* Programming and Problem Solving II 41


Example: passing arguments by value
#include <stdio.h>
main()
{ a and b
int a, b; do not
a = 5 ; b = 20 ; swap
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; x and y swap
y=t;
}
* Programming and Problem Solving II 42
Example: passing arguments by reference
#include <stdio.h>
main()
{ *(&a) and *(&b)
int a, b; swap
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 and *y
*x = *y ; swap
*y = t ;
}
* Programming and Problem Solving II 43
Pointer to Pointer

A pointer to a pointer is a form of multiple


indirection, or a chain of pointers
The first pointer is used to store the address of the
variable.
The second pointer is used to store the address of the
first pointer- known as double pointers.
Syntax:
int **ptr; // declaring double pointers

* Programming and Problem Solving II 44


Pointer to Pointer

* Programming and Problem Solving II 45


Pointer to Pointer

* Programming and Problem Solving II 46


Pointer to Pointer
int main()
{
int var = 789;
int *ptr2; // pointer for var
int **ptr1; // double pointer for ptr2
ptr2 = &var; // storing address of var in ptr2
ptr1 = &ptr2; // Storing address of ptr2 in ptr1
printf("Value of var = %d\n", var ); // Displaying value of var using
// both single and double pointers
printf("Value of var using single pointer = %d\n", *ptr2 );
printf("Value of var using double pointer = %d\n", **ptr1);
return 0;
}
Output
Value of var = 789
Value of var using single pointer = 789
Value of var using double pointer = 789
* Programming and Problem Solving II 47
Dynamic Memory Allocation

* Programming and Problem Solving II 48


Basic Idea

• Many a time we face situations where data is


dynamic in nature.
– Amount of data cannot be predicted beforehand.
– Number of data item keeps changing during
program execution.
• Such situations can be handled more easily and
effectively using dynamic memory management
techniques.

* Programming and Problem Solving II 49


Contd.

• C language requires the number of elements in


an array to be specified at compile time.
– Often leads to wastage or memory space or program
failure.
• Dynamic Memory Allocation
– Memory space required can be specified at the time
of execution.
– C supports allocating and freeing memory
dynamically using library routines.

* Programming and Problem Solving II 50


Memory Allocation Process in C

Local variables Stack

Free memory Heap

Global variables Permanent storage


area
Instructions

* Programming and Problem Solving II 51


Contd.

• The program instructions and the global


variables are stored in a region known as
permanent storage area.
• The local variables are stored in another area
called stack.
• The memory space between these two areas is
available for dynamic allocation during
execution of the program.
– This free region is called the heap.
– The size of the heap keeps changing

* Programming and Problem Solving II 52


Memory Allocation Functions

• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.

* Programming and Problem Solving II 53


Allocating a Block of Memory

• A block of memory can be allocated using the


function malloc.
– Reserves a block of memory of specified size and
returns a pointer of type void.
– The return pointer can be assigned to any pointer
type.
• General format:
ptr = (type *) malloc (byte_size) ;

* Programming and Problem Solving II 54


Contd.

• Examples
p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the size of an int”
bytes is reserved.
• The address of the first byte of the allocated memory is
assigned to the pointer p of type int.
p

400 bytes of space

* Programming and Problem Solving II 55


Contd.

cptr = (char *) malloc (20) ;


• Allocates 10 bytes of space for the pointer cptr of type char.

sptr = (struct stud *) malloc (10 *


sizeof (struct stud));

* Programming and Problem Solving II 56


Points to Note

• malloc always allocates a block of contiguous


bytes.
– The allocation can fail if sufficient contiguous
memory space is not available.
– If it fails, malloc returns NULL.

* Programming and Problem Solving II 57


Example
#include <stdio.h> printf("Input heights for %d

main() Input the number of students.students \n",N);


5 for(i=0;i<N;i++)
{ scanf("%f",&height[i]);
Input heights for 5 students
int i,N;
23 24 25 26 27
float *height; for(i=0;i<N;i++)
Average height= 25.000000
float sum=0,avg; sum+=height[i];

printf("Input the number of students. \n"); avg=sum/(float) N;


scanf("%d",&N);
printf("Average height= %f \n",
height=(float *) malloc(N * sizeof(float)); avg);
}

* Programming and Problem Solving II 58


Releasing the Used Space

• When we no longer need the data stored in a


block of memory, we may release the block for
future use.
• How?
– By using the free function.
• General format:
free (ptr) ;
where ptr is a pointer to a memory block which
has been already created using malloc.

* Programming and Problem Solving II 59


Altering the Size of a Block

• Sometimes we need to alter the size of some


previously allocated memory block.
– More memory needed.
– Memory allocated is larger than necessary.
• How?
– By using the realloc function.
• If the original allocation is done by the statement
ptr = malloc (size) ;
then reallocation of space may be done as
ptr = realloc (ptr, newsize) ;

* Programming and Problem Solving II 60


Contd.

– The new memory block may or may not begin at the


same place as the old one.
• If it does not find space, it will create it in an entirely
different region and move the contents of the old block into
the new block.
– The function guarantees that the old data remains
intact.
– If it is unable to allocate, it returns NULL and frees
the original block.

* Programming and Problem Solving II 61

You might also like