You are on page 1of 28

Fo

rA
pt
ec
h
C
en
tre
Session 8

U
Pointers

se
O
nl
y
y
Objectives

nl
O
se
 Explain what a pointer is and where it is used

U
 Explain how to use pointer variables and pointer

tre
operators

en
 Assign values to pointers
C
 Explain pointer arithmetic
h
 Explain pointer comparisons
ec
pt

 Explain pointers and single dimensional arrays


rA

 Explain Pointer and multidimensional arrays


Fo

 Explain how allocation of memory takes place


Elementary Programming with C/Session 8/ 2 of 28
y
What is a Pointer?

nl
O
se
 A pointer is a variable, which contains the address of a

U
memory location of another variable

tre
 If one variable contains the address of another

en
variable, the first variable is said to point to the second
variable
C
 A pointer provides an indirect method of accessing the
h
ec

value of a data item


pt

 Pointers can point to variables of other fundamental data


rA

types like int, char, or double or data aggregates like


arrays or structures
Fo

Elementary Programming with C/Session 8/ 3 of 28


y
What are Pointers used for?

nl
O
se
Some situations where pointers can be used are -

U
tre
 To return more than one value from a function

en
 To pass arrays and strings more conveniently from
C
one function to another
h
 To manipulate arrays easily by moving pointers to them
ec

instead of moving the arrays itself


pt

 To allocate memory and access it


rA

(Direct Memory Allocation)


Fo

Elementary Programming with C/Session 8/ 4 of 28


y
Pointer Variables

nl
O
se
U
A pointer declaration consists of a base type and a variable

tre
name preceded by an *

en
General declaration syntax is :
C
type *name;
h
ec
pt

For Example:
rA

int *var2;
Fo

Elementary Programming with C/Session 8/ 5 of 28


y
Pointer Operators

nl
O
se
 There are 2 special operators which are used with pointers

U
:
& and *

tre
 The & operator is a unary operator and it returns the

en
memory address of the operand
C
var2 = &var1;
h
ec

 The second operator * is the complement of &. It is a unary


pt

operator and returns the value contained in the memory


rA

location pointed to by the pointer variable’s value


temp = *var2;
Fo

Elementary Programming with C/Session 8/ 6 of 28


Assigning Values To

y
Pointers-1

nl
O
se
 Values can be assigned to pointers through the & operator.

U
tre
ptr_var = &var;

en
C
 Here the address of var is stored in the variable ptr_var
h
 It is also possible to assign values to pointers through another
ec

pointer variable pointing to a data item of the same data type


pt

ptr_var = &var;
rA
Fo

ptr_var2 = ptr_var;
Elementary Programming with C/Session 8/ 7 of 28
Assigning Values To

y
Pointers-2

nl
O
se
U
 Variables can be assigned values through their pointers as

tre
well

en
*ptr_var = 10;
C
h
ec
pt

 The above declaration will assign 10 to the variable var if


rA

ptr_var points to var


Fo

Elementary Programming with C/Session 8/ 8 of 28


y
Pointer Arithmetic-1

nl
O
se
 Addition and subtraction are the only operations that

U
can be performed on pointers

tre
en
C
h
 Let us assume that var is stored at the address
ec

1000
pt
rA

 Then ptr_var has the value 1000 stored in it. Since integers are 2
bytes long, after the expression “ptr_var++;” ptr_var will have the
Fo

value as 1002 and not 1001

Elementary Programming with C/Session 8/ 9 of 28


y
Pointer Arithmetic-2

nl
O
se
U
tre
en
C
 Each time a pointer is incremented, it points to the
h
ec

memory location of the next element of its base type


 Each time it is decremented it points to the location of the
pt

previous element
rA

 All other pointers will increase or decrease depending on


Fo

the length of the data type they are pointing to


Elementary Programming with C/Session 8/ 10 of 28
y
Pointer Comparisons

nl
O
se
 Two pointers can be compared in a relational expression provided both
the pointers are pointing to variables of the same type

U
tre
 Consider that ptr_a and ptr_b are 2 pointer variables, which point to
data elements a and b. In this case the following comparisons are

en
possible:

C
h
ec
pt
rA
Fo

Elementary Programming with C/Session 8/ 11 of 28


Pointers and Single

y
Dimensional Arrays-1

nl
O
se
U
 The address of an array element can be expressed in two

tre
ways :

en
• By writing the actual array element preceded by
C
the ampersand sign (&)
h
ec

• By writing an expression in which the subscript is


pt

added to the array name


rA
Fo

Elementary Programming with C/Session 8/ 12 of 28


Pointers and Single

y
Dimensional Arrays-2

nl
O
se
Example

U
#include<stdio.h>
void main()

tre
{
static int ary[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

en
int i;

C
for (i = 0; i < 10; i ++)
{
h
printf(“\ni=%d,aryi]=%d,*(ary+i)=%d“,i,
ec

ary[i],*(ary + i));
pt

printf(“&ary[i]= %X,ary+i=%X”,&ary[i],ary+i);
/* %X gives unsigned hexadecimal */
rA

}
}
Fo

Elementary Programming with C/Session 8/ 13 of 28


Pointers and Single

y
Dimensional Arrays-3

nl
O
se
Output

U
tre
en
C
h
ec
pt
rA
Fo

Elementary Programming with C/Session 8/ 14 of 28


Pointers and Multi

y
Dimensional Arrays-1

nl
O
se
U
 A two-dimensional array can be defined as a pointer to a
group of contiguous one-dimensional arrays

tre
en
 A two-dimensional array declaration can be written as :
C
data_type (*ptr_var) [expr 2];
h
ec

instead of
pt
rA

data_type (*ptr_var) [expr1] [expr 2];


Fo

Elementary Programming with C/Session 8/ 15 of 28


y
Pointers and Strings-1

nl
O
se
#include <stdio.h>
#include <string.h> Example

U
void main ()

tre
{
char a, str[81], *ptr;

en
printf(“\nEnter a sentence:”);
gets(str);
C
printf(“\nEnter character to search for:”);
h
a = getche();
ec

ptr = strchr(str,a);
/* return pointer to char*/
pt

printf( “\nString starts at address: %u”,str);


rA

printf(“\nFirst occurrence of the character is at


address: %u ”,ptr);
Fo

printf(“\n Position of first occurrence(starting from


0)is: % d”, ptr_str);
} Elementary Programming with C/Session 8/ 16 of 28
y
Pointers and Strings-2

nl
O
se
Output

U
tre
en
C
h
ec
pt
rA
Fo

Elementary Programming with C/Session 8/ 17 of 28


y
Allocating Memory-1

nl
O
se
U
The malloc() function is one of the most

tre
commonly used functions which permit

en
allocation of memory from the pool of free
C
memory. The parameter for malloc() is an
h
ec

integer that specifies the number of bytes


pt

needed.
rA
Fo

Elementary Programming with C/Session 8/ 18 of 28


y
Allocating Memory-2

nl
O
se
Example

U
tre
en
C
h
ec
pt
rA
Fo

Elementary Programming with C/Session 8/ 19 of 28


y
free()-1

nl
O
se
free() function can be used to de-allocates (frees) memory

U
when it is no longer needed.

tre
Syntax:

en
void free(void *ptr );
C
h
This function deallocates the space pointed to by ptr,
ec

freeing it up for future use.


pt
rA

ptr must have been used in a previous call to malloc(),


Fo

calloc(), or realloc().
Elementary Programming with C/Session 8/ 20 of 28
y
free()-2

nl
O
se
#include <stdio.h>
#include <stdlib.h> /*required for the malloc and free functions*/

U
int main()

tre
{
int number;
Example

en
int *ptr;
int i;
C
printf("How many ints would you like store? ");
h
scanf("%d", &number);
ec

ptr = (int *) malloc (number*sizeof(int)); /*allocate memory


*/
pt

if(ptr!=NULL)
rA

{
for(i=0 ; i<number ; i++)
Fo

{
*(ptr+i) = i; Contd…
} Elementary Programming with C/Session 8/ 21 of 28
y
free()-3

nl
O
se
for(i=number ; i>0 ; i--)
Example

U
{
printf("%d\n",*(ptr+(i-1))); /* print out

tre
in reverse order */
}

en
free(ptr); /* free allocated memory */

}
return 0;
C
h
else
ec

{
pt

printf("\nMemory allocation failed - not


enough memory.\n");
rA

return 1;
}
Fo

Elementary Programming with C/Session 8/ 22 of 28


y
calloc()-1

nl
O
se
calloc is similar to malloc, but the main difference is that the

U
values stored in the allocated memory space is zero by default

tre
calloc requires two arguments

en

 The first is the number of variables you'd like to allocate memory for

C
The second is the size of each variable
h
ec

Syntax :
pt
rA

void *calloc( size_t num, size_t size );


Fo

Elementary Programming with C/Session 8/ 23 of 28


y
calloc()-2

nl
O
se
#include <stdio.h> Example

U
#include <stdlib.h>

tre
int main()
{

en
float *calloc1, *calloc2;
int i;

C
calloc1 = (float *) calloc(3, sizeof(float));
calloc2 = (float *)calloc(3, sizeof(float));
h
if(calloc1!=NULL && calloc2!=NULL)
ec

{
for(i=0 ; i<3 ; i++)
pt

{
rA

printf("calloc1[%d] holds %05.5f ", i, calloc1[i]);


printf("\ncalloc2[%d] holds %05.5f ", i,
Fo

*(calloc2+i));
}
Contd……
Elementary Programming with C/Session 8/ 24 of 28
y
calloc()-3

nl
O
se
free(calloc1); Example

U
free(calloc2);

tre
return 0;

en
}
else
{ C
h
ec

printf("Not enough memory\n");


return 1;
pt

}
rA

}
Fo

Elementary Programming with C/Session 8/ 25 of 28


y
realloc()-1

nl
O
se
You've allocated a certain number of bytes for an array but later find

U
that you want to add values to it.You could copy everything into a
larger array, which is inefficient, or you can allocate more

tre
bytes using realloc, without losing your data.

en

 C
realloc takes two arguments
The first is the pointer referencing the memory
h
 The second is the total number of bytes you want to reallocate
ec
pt

Syntax:
rA
Fo

void *realloc( void *ptr, size_t size );

Elementary Programming with C/Session 8/ 26 of 28


y
realloc()-2

nl
O
se
#include<stdio.h>
#include <stdlib.h> Example

U
int main()

tre
{
int *ptr;

en
int i;
ptr = (int *)calloc(5, sizeof(int *));
if(ptr!=NULL)
{ C
h
*ptr = 1; *(ptr+1) = 2;
ec

ptr[2] = 4; ptr[3] = 8; ptr[4] = 16;


ptr = (int *)realloc(ptr, 7*sizeof(int));
pt

if(ptr!=NULL)
rA

{
printf("Now allocating more memory... \n");
Fo

ptr[5] = 32; /* now it's legal! */


ptr[6] = 64;

Elementary Programming with C/Session 8/ 27 of 28


y
realloc()-3

nl
O
se
for(i=0 ; i<7 ; i++)
{ Example

U
printf("ptr[%d] holds %d\n", i, ptr[i]);
}

tre
realloc(ptr,0); /* same as free(ptr); - just fancier! */
return 0;

en
}
else
{ C
h
printf("Not enough memory - realloc failed.\n");
ec

return 1;
}
pt

}
else
rA

{
printf("Not enough memory - calloc failed.\n");
Fo

return 1;
}
} Elementary Programming with C/Session 8/ 28 of 28

You might also like