0% found this document useful (0 votes)
16 views41 pages

AOP Unit 2 Chapter 3.Pptx

Uploaded by

meghanar2910
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)
16 views41 pages

AOP Unit 2 Chapter 3.Pptx

Uploaded by

meghanar2910
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/ 41

THE ART OF COMPUTER

PROGRAMMING
Unit 2-Chapter 3-Pointers
Dr. Salini Suresh
Associate Professor ,DSCASC
Pointers
Whenever a variable is declared like int, char, float etc. The
declaration tells the compiler to :
1) Reserve space in memory depending on the datatype.
2) Associate the variable name with that memory location.
3) To Store the respective value at that location.

Ex. : int i = 3;
The Memory Map will be :
Pointers
The normal variable when declared always stores the value
of the variable and not the address.

There is another variable available in C which can store


only the address of another variable, it is called as
pointer variable.

Pointer is a variable which is used to store only the


address of another variable using pointer operator * at
the time of declaration.
Advantages of Pointers
1. Pointers are more efficient in handling arrays and data
tables.
2. Pointers reduce length and complexity of programs.
3. Pointers reduce the execution speed and thus reduce the
program execution time.
4. Can be used to return multiple values from the functions via
function arguments.
5. The use of pointer arrays to character strings results in
saving of data storage space in memory.
6. Pointers allows C to support dynamic memory management.
7. They are an efficient tool for manipulating dynamic data
structures such as structures, linked list, queues, stacks and
trees.
Pointers
Declaration of pointer variable :
Syntax: Pointer declaration styles:
1. int* p;
Datatype *pointer variable name; 2. int *p;
3. int * p;
Eg.: 1) int *ptr;
Declares a pointer by name ptr which can store the address of only the
integer variable.

2 ) float *ptr ;
Declares a pointer by name ptr which can store the address of only the float
variable.

POINTER OPERATOR :
It is the ‘*’ which is used at the time of declaration of the variable to
identify the variable as a pointer and not a normal variable.
ASSIGNING THE VALUE TO THE POINTERS
Once the pointer is declared it must be assigned with the address of the
variable which is pointed to.

It can only be assigned with the address of another variable and not by the
value directly.

It is assigned by using ‘&’ symbol.

Eg. : int n = 10, *ptr;


ptr = &n;

The memory map of n & ptr in the above example will be :


POINTERS
//Program to illustrate the creation and printing of pointer
//variable

# include <stdio.h>
void main ( )
{
int n, *ptr;
ptr = &n;
n = 10;
printf (“ The value of n = %d”, n);
printf (“The address of n = %u”, ptr);
}
Accessing a value through a POINTER
INDIRECT OPERATOR :

It is the operator used along with the pointer to access the value
stored at the address of variable referred by the pointer.

It is the ‘*’ symbol used in expression along with the pointer


variable.

Ex.: int i = 5, x;
int *p;
p = &i;
x = *p;

The value of p= 2005 i.e. the address of i &


The value of x = 5 i.e., the value at the address of i.
POINTERS
Differentiate between ptr and *ptr if the ptr is a pointer
used to store address of integer variable.

ptr is a integer pointer which stores the address of integer


variable, where as

*ptr access the value at the address of integer variable to


which ptr is pointed.
Chain of Pointers
It is possible to make a pointer to point to another pointer, thus creating a
chain of pointers.

P2 P1 variable

Address 2 Address 2 Value

Here pointer variable p2 contains the address of the pointer variable p1,
which points to the location that contains the desired value.
This is known as multiple indirections.

A variable that is a pointer to a pointer must be declared using additional


indirection operator symbol in front of the name.
Ex: int **p2;
Chain of Pointers
Ex:
main()
{
int x, *p1, **p2;
x=100;
p1= &x;
p2= &p1;
printf(“%d”, **p2);
}

This code will display the value 100.

Here, p1 is declared as a pointer to an integer and p2 as a pointer to a


pointer to an integer.
Pointer Expression and Pointer Arithmetic
Whenever a pointer has to be used in the arithmetic expression it has to be
used along with indirect operator (‘*’) before the pointer variable.

It performs the operation not on the address but on the value at the address
which is pointed to.

Eg.: If ptr & ptr1 are two pointer variables storing the address of a & b
respectively with the value 10 and 5 then the following arithmetic
expression will result in
*ptr + *ptr1
= 10 + 5 = 15.
*ptr + 10
= 10 + 10 = 20.
*ptr1 ++
= 5++ = 6.
ptr1++ will increment to next location.
Pointer increments And scale factor
Pointers can be incremented like
p1= p2 + 2;
p1 = p1 + 1; or p1++;

If p1 is an integer pointer pointer with an initial value 2800, then after the
operation p1=p1+1, the value of p1 will be 2802 and not 2801.

When we increment a pointer, it’s value is increased by the ‘ length’ of the


datatype that it points to. This length is called the scale factor.

The length of the various data types are:


Characters 1 byte
Integers 2 bytes
Floats 4 bytes
Double 8 bytes
Pointers And Arrays
The declaration int a[10];
defines an array of size 10, that is, a block of 10 consecutive objects named
a[0], a[1], ..., a[9].
Pointers And Arrays

The relationship between p and x is shown as:

P = &x[0] (=1000)
P+1= &x[1] (=1002)
P+2= &x[2] (=1004)
P+3= &x[3] (=1006)
P+4= &x[4] (=1008)

The address of an element is calculated using its index and the scale
factor of the data type.

Ex: address of x[3]= base address + (3 * scale factor of int)


= 1000 + (3 *2) = 1006
Pointers And Arrays
The notation a[i] refers to the i-th element of the array.
If pa is a pointer to an integer, declared as int *pa;
then the assignment pa = &a[0]; sets pa to point to element zero of a;
that is, pa contains the address of a[0].
Now the assignment x = *pa; will copy the contents of a[0] into x.
Pointers And Arrays
If pa points to a particular element of an array, then by definition pa+1 points to
the next element,
pa+i points i elements after pa, and pa-i points i elements before. Thus, if pa
points to a[0], *(pa+1) refers to the contents of a[1],
pa+i is the address of a[i], and *(pa+i) is the contents of a[i].
Accessing one dimensional array elements using the pointer

main()
{
int *p, i;
int x[5] = {5, 9, 6, 3, 7};
i=0;
p=x;
printf (“ Element Value ”);
while(i<5)
{
printf(“ x[%d] %d ”, i, *p);
i++;
++p;
}
}
Accessing one dimensional array elements using the pointer
0 1 2 3 4 5
0
1
2
3
4
5
6

If p - Pointer to first row


p+i - pointer to ith row
*(p+i) - pointer to first elemnt in ith row
*(p+i)+j -pointer to jth element in the ith row
*(*(p+i)+j)-value stored in the cell (i,j)
Array of Pointers
“Array of pointers” is an array of the pointer variables.
.
It is also known as pointer arrays.

Syntax:
int *var_name[array_size];

Declaration of an array of pointers:


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

We can make separate pointer variables which can point to the different values or
we can make one integer array of pointers that can point to all the values
Array of Pointers
// C program to demonstrate example of array of pointers.
#include <stdio.h>
const int SIZE = 3;
void main()
{
// creating an array
int arr[] = { 1, 2, 3 };

// we can make an integer pointer array to storing the address of array elements
int i, *ptr[SIZE];

for (i = 0; i < SIZE; i++) {


// assigning the address of integer.
ptr[i] = &arr[i];
}
// printing values using pointer
for (i = 0; i < SIZE; i++) {
printf("Value of arr[%d] = %d\n", i, *ptr[i]);
}
}
Pointers And Functions
There are two methods of passing the values between functions:

1.Call by value method


2.Call by reference method

Pointers are normally used within the function to pass reference of


the variable between functions.

It is mainly used to call value or function by reference & not by


value.

It is also used to return more than one value


Pointers And Functions
1) Call by value:

In this method the values of actual argument are passed from


calling function to the formal arguments of called function.

In this case the values of each actual arguments are copied onto the
corresponding formal arguments of the called function.
Call by value:
C program to illustrate call by value
#include<stdio.h> • Since the values are passed the
void num(int,int); changes made to the formal
void main() arguments within ,
{ • the called function will not have
int a=10,b=20; any effect on the values of actual
printf(“a= %d and b=%d before the function call “, a,b); arguments in the calling function.
num(a, b);
printf(“a= %d and b=%d after the function call using call by value
“);
}

void num(int m, int n)


{
m = m + 30;
n = n + 100;
}

Output :
a=10 and b=20 before the function call
a=10 and b=20 after the function call using call by value
Pointers And Functions
2) Call by Reference:

In this method the address of the actual parameters & not the
values are passed into the formal argument of the called function.

Since the address is passed the formal arguments within the


called function will directly affect the values of actual arguments.
C program to illustrate call by reference method
#include<stdio.h>
void num(int*,int*);
void main()
{
int a=10,b=20;
printf(“a= %d and b=%d before the function call “, a,b);
num(&a,&b);
printf(“a= %d and b=%d after the function call using call by reference “);
}
void num(int *m, int *n)
{
*m=*m+30;
*n=*n+10;
}
Output :
a=10 and b=20 before the function call
a=40 and b=30 after the function call using call by reference
Differentiate between call by value and call by
reference
Functions returning pointers
Since pointers are a datatype in C, we can also force a function to return a
pointer to the calling function.

Ex: int *larger ( int *, int *); output:


main() 20
{
int a=10;
int b=20;
int *p;
p= larger(&a, &b);
printf( “%d”, *p);
}
int *larger (int *x, int *y)
{
if ( *x > *y)
return(x);
else
return(y);
}
Pointers to Functions
A pointer to a function is declared as follows:
type (*fptr) ();

This tells the compiler that fptr is a pointer to a function, which returns
type value.

The parentheses around *fptr are necessary.

Ex: double mul(int, int);


double (*p1) ();
p1=mul;

This declares p1 as a pointer to a function and mul as a function and then


make p1 to point to the function mul.

To call the function mul, we may use


(*p1)(x,y) which is equivalent to mul(x,y)
Multi-Dimensional Arrays

• Multidimensional arrays are derived from the basic or built-in data


types of the C language.
• Two-dimensional arrays are understood as rows and columns
• Mostly Two-dimensional array are used in Multi-dimensional array.
Multi-Dimensional Arrays
Two dimensional array:

General form of declaring N-dimensional arrays:


data_type array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array.


array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions

Examples:
Two dimensional array:
int two_d[10][20];

Three dimensional array:


int three_d[10][20][30];
Size of multidimensional arrays
Total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Two-Dimensional Array
The basic form of declaring a
two-dimensional array of size x, y:
Syntax:
data_type array_name[x][y];
data_type: Type of data to be stored.
• Elements in two-dimensional arrays
are commonly referred by x[i][j]
where i is the row number and ‘j’ is
the column number. A two – dimensional array ‘x’ with 3 rows and 3
columns
• A two – dimensional array can be
seen as a table with ‘x’ rows and ‘y’
columns where the row number
ranges from 0 to (x-1) and column
number ranges from 0 to (y-1)
Initializing Two – Dimensional Arrays:
• int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
• This type of initialization make use of nested braces.
• Each set of inner braces represents one row.
• In the above example there are total three rows so there are three
sets of inner braces.
Accessing Elements of Two-Dimensional
Arrays
Elements in Two-Dimensional arrays are accessed using the row
indexes and column indexes.

Example:int x[2][1];
The above example represents the element present in third row and
second column.

Note: In arrays if size of array is N. Its index will be from 0 to N-1.


Therefore, for row index 2 row number is 2+1 = 3.
A program to input elements in a two dimensional array and print it.
#include<stdio.h>
#include<conio.h>
void main()
{ int a[3][3];
int i,j;
clrscr();
printf(“enter the elements in the array:”);
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
printf(“%d”,a[i][j]);
} printf(“\n”);
}
getch();
}
Initialization of Pointer Arrays
Consider the example • name is an array of character pointers
char *month_name(int n) • The initializer is a list of character strings;
{ • each is assigned to the corresponding
position in the array.
static char *name[] = {
• The characters of the i-th string are
"Illegal month", placed somewhere,
"January", "February", "March", • and a pointer to them is stored in
"April", "May", "June", name[i].
"July", "August", "September", • Since the size of the array name is not
specified, the compiler counts the
"October", "November", "December" initializers
}; • and fills in the correct number
return (n < 1 || n > 12) ? name[0] : •,
name[n];
}
Command-line Arguments
In environments that support C, there is a way to pass command-line arguments
or parameters to a program when it begins executing.

The command line arguments are handled using main() function arguments.

When main is called, it is called with two arguments.

1.Argc ( argument count) is the number of command-line arguments


2. argv( argument vector) is a pointer to an array of character strings that
contain the arguments
Command-line Arguments-eg
Consider program echo, which echoes its command-line arguments on a single line, separated
by blanks.
That is, the command ----🡪 echo hello, world
prints the output
hello, world
In the example above, argc is 3,
and argv[0], argv[1], and argv[2] are "echo", "hello,", and "world“ respectively.
The first argument is argv[1] and the last is argv[argc-1];
.

argv as an array of character pointers


Example -checks if there is any argument supplied from the command line

#include <stdio.h>
When the above code is compiled and
int main( int argc, char *argv[] ) { executed with single argument, it produces
the following result.
if( argc == 2 ) { The argument supplied
printf("The argument supplied is %s\n",
argv[1]); When the above code is compiled and
} executed with a two arguments, it produces
else if( argc > 2 ) { the following result.
printf("Too many arguments supplied.\n"); Too many arguments supplied.
}
else { When the above code is compiled and
printf("One argument expected.\n"); executed without passing any argument, it
} produces the following result.
} One argument expected

You might also like