Você está na página 1de 34

Pointer and pointer

applications
To me the very
essence of education is
concentration of mind
not collection of facts
- Swami Vivekananda
POINTERS

 Accessing variables through pointers


 Pointer Declaration and definitions

 Initialization of pointer variables

 Pointers and functions

 Pointers to pointers 3 hrs.


Behrouz A. Forouzan, Richard F. Gilberg “A Structured Programming Approach Using C”,
Thomson, 2ndEdition, 2003.

7/24/2019 Smitha N Pai 2


Smitha N Pai 7/24/2019

POINTERS
 A derived data type –built from standard types
 Value is one of the addresses available in the
computer for storing and accessing data
 Address of a variable is the address of the first Value of p
is (&b)
byte
Integer
occupied by that variable b -123
constants Variable Integer
name value p
-123
a -123 234560
.
_____
.
b 145 234564 &b
.
stored in Pointer
145
variable variable
.
Integer Address
. 234564
variable of p
.
variable b
3
Smitha N Pai 7/24/2019
ACCESSING VARIABLES THROUGH
POINTERS

 Dereferencing a pointer –use value to reference


(address) another variable
 Indirection operator (*) is a unary operator whose
operand must be a pointer value
e.g. p=&a;
a++ a=a+1 *p=*p+1 (*p)++ different from *p++
Priority of unary operator * is 15, post fix increment ++ is 16
& is inverse of *
*(&x) is same as x

4
Smitha N Pai 7/24/2019
POINTER DECLARATION AND DEFINITION
AND INITIALIZATION
char *p; //declaration (Step 1)
char a;
b 14
p=&a;//initialization (Step 2)
*p=‘b’;
int b =14; p 135764
int *q=&b;
float *r=NULL;
Deferecing null pointer we get the address zero which is the physical address zero
or first address location of the program area

e.g. Give example for a) three variables one pointer b)One variable three pointers

Pointer type

type * identifier
5
Smitha N Pai 7/24/2019

POINTERS AND FUNCTIONS

E.g.
exchange (&a, &b);// in the main program
exchange (int *, int *) {…..}
Everytime we want a called function to have access
to a variable in the calling function, we send the
address of that variable to the called function and
use the indirection operator to access it
It is an error to return a pointer to a local variable

6
Smitha N Pai 7/24/2019

POINTER TO POINTER

 Each level of pointer indirection requires a


separate indirection operator when it is
dereferenced.
 Write code to do the following

p q r s

7
POINTER APPLICATIONS

“Education is the ability to listen to almost anything without losing


your temper or your self-confidence.”
― RobertFrost
Smitha N Pai 7/24/2019

POINTER APPLICATIONS

 Arrays and pointers


 Pointer arithmetic and arrays

 Passing an array to a function

 Understanding complex declarations

 Memory allocation functions

 Array of pointers.

9
Arrays and pointers
 Name of an array is a pointer constant to the first
element whose value cannot be changed
 Address and name refer to the same location in the
memory which is inter-changable provided it is
used as rvalue
 Dereferencing array name dereference the first
element of the array referring to a[0]
 ais same as &a[0] where a is the pointer to the
first element and not the whole array

10
Smitha N Pai 7/24/2019
What is the output ?
main()
{
int a[5]= {2,5,7,6,3};
int *p=a;
int i=0;
printf(“%d %d \n “, a[i], *p);
return;
}

11
Smitha N Pai 7/24/2019
Use of multiple names for a array to reference
difference location at the same time
main()
{
int a[5]= {2,5,7,6,3};
int *p=&a[1];
printf(“%d %d \n “, a[0], p[-1]);
printf(“%d %d \n “, a[1], p[0]);
return;
}

12
Smitha N Pai 7/24/2019
Pointer arithmetic and arrays
 Pointer arithmetic offers restricted set of arithmetic
operations for manipulating the addresses in
pointers
 Useful to move through an array from element to
element
 Given pointer p, p+n is a pointer to the value,
which is n elements away, where n is an offset from
the original pointer

13
Smitha N Pai 7/24/2019
Pointer and one dimensional arrays
 Size of an element is determined by the type of the
pointer
 Pointers of different types cannot be assigned to
one another
 Address=pointer + (offset * size of element)

 a+n= a +n* sizeof (one element)

 *( a +n) is identical to a[n]

14
Smitha N Pai 7/24/2019
Pointers and other operators
 Operation on pointers
 Addition of pointer and integer, pointer and pointer
 Subtraction is only between two pointers or first is a
pointer and the second is an integer
 Pointers can have postfix and unary operators

 Result of subtraction is an index representing the


number of elements between two pointers-Meaningful if
two pointers are associated with same array structure.
 Relational operators are allowed only if both operands
are pointers of the same type

15
Smitha N Pai 7/24/2019
Examples
 p+5
 5+p
 p-5
 p1-p2
 p++
 --p
 p1>=p2
 p1!=p2
 if (ptr ==NULL) same as if (!ptr)
 if (ptr!=NULL) is same as if(ptr)
16
Smitha N Pai 7/24/2019
Pointers and two dimensional arrays
 Name of the array is a pointer constant to the first
element of the array – which is another array
 Dereferencing array name, we get another pointer to
one dimensional array
 table[0] is identical to *(table+0) where table is a two
dimensional array.
 To refer to a row, dereference the array pointer which
gives a pointer to a row
 Given pointer to a row, dereference the row pointer to
get individual element
 Double reference is given as *(*(table))
 table[i][j] is identical to *(*(table +i) +j)

17
Smitha N Pai 7/24/2019
Passing an array to a function
 Array name itself is a pointer constant which is the
address of the first element in the array
 Array notation to declare/define an array in the
function
 int func(int arr[]) { }
 Using pointers
 int func(int *p) { }
 For multidimensional use the array syntax in the
header declaration and definition
 float func(int bigarr[][4][5])
19
Smitha N Pai 7/24/2019
Understanding complex declaraions
Identifier

6 4 2 Start here 1 3 5
 int x ; “x is # an integer”
 int x #
2 0 1
 int * p # # ; “p is #a pointer #to an integer”
 int table [4] ; “table is an array of 4 integers”
 int table [4][5] ;“table is an array of [4][5]integers”
 int * arrofptr[5] # ;arr is an array of 5 pointers to #

integer Smitha N Pai 7/24/2019


20
Understanding complex declaraions
 int (*ptrarr # ) [5] ; “prtarry is a pointer # to an array
of 5 integers”
 int func(…) ; “func is a function returning an
integer”
 int * func(int ) # ;” func is a function returning a
pointer to an integer”

21
Smitha N Pai 7/24/2019
Memory allocation functions
 Static and dynamic
 Static memory allocation –Declaration and
definition of memory fully specified in source
program
 Number of bytes reserved cannot be changed
during run time
 Should know exactly what is the data requirement

22
Smitha N Pai 7/24/2019
Memory allocation functions(contd)
 Dynamic memory allocation- Memory allocation
at execution
 Uses predefined functions to allocate and release
memory for data while program is running
 Postpones the data definition to run time

 Programmer must use either standard data types or


must have declared any derived data type

23
Smitha N Pai 7/24/2019
Memory usage
 Memory management functions used with dynamic
memory
 Memory management functions -malloc, calloc,
realloc for memory allocation and free to return
memory not in use - in standard library header file
<stdlib.h>
 Memory = Program memory+ data memory
 Program memory = main + called functions
 Data memory = permanent definitions (global data
and constants) + local definitions + dynamic data
memory
24
Smitha N Pai 7/24/2019
Memory usage(contd.)
 Main is memory all the time
 Each called function is in memory only while it or
any of its called functions are active – most system
keep all functions in memory while the program is
running
 Program code for function is in memory at all times

 Local variable is available only when it is active

25
Smitha N Pai 7/24/2019
Memory usage(contd.)
 More than one version of the function can be active
at a time
 If multiple copies of local variable are allocated
although only one copy of the function is present
 Memory facility for this capability is stack
 Heap is unused memory allocated to the program
and available to be assigned during its execution
 It is a memory pool from which memory is
allocated when requested by the memory allocation
functions
26
Smitha N Pai 7/24/2019
Memory Allocation ( malloc)
 Allocates a block of memory that contains the number
of bytes specified in its parameter
 Returns void pointer to the first byte of the allocated
memory
 Allocated memory is not initialized – contains garbage
 void *malloc(size_t size); where size_t is an unsigned
integer and is guaranteed to be large enough to hold the
maximum address of the computer
 e.g.
 pint = (int *) malloc (sizeof (int));
 malloc returns the address of the first byte in the memory
space allocated on success or NULL otherwise
27
Smitha N Pai 7/24/2019
malloc (contd.)
 Attempt to allocate memory from the heap when
memory is insufficient is known as overflow.
 If unchecked in the program, it produces invalid
results or aborts with an invalid address, the first
time the pointer is used
 Memory is allocated in the heap only through a
pointer and does not have its own identifier
 Attempting to allocate a size zero memory- results
unpredictable could return NULL or
implementation dependant value
 if (!ptr =(int *) malloc (sizeof(int)))) exit (100);
28
Smitha N Pai 7/24/2019
Contiguous memory allocation -calloc
 Used to allocate memory for arrays
 It allocates contiguous block of memory large enough
to contain an array of elements of a specified size
 It returns a pointer to the first element of the allocated
array
 The size associated with its pointer is the size of one
element not the entire array
 It clears the memory- the memory it allocates is set to
zero
 Zero value is not guaranteed to be null value for types
other than integer – null for characters is space and
null for float may have a different format
29
Smitha N Pai 7/24/2019
Calloc (contd.)
 Prototype
 void * calloc(size_t element-count, size_t element-size);
 e.g.
 if (!ptr=(int *)calloc(200,sizeof(int)))) exit(100);

30
Smitha N Pai 7/24/2019
Reallocation of memory allocation (realloc)
 Given a pointer to a previously allocated block of
memory, realloc changes the size of the block by
deleting or extending the memory at the end of the
block
 If the memory cannot be extended because of other
allocations, realloc allocates a completely new block,
copies the existing memory allocation to the new
allocation and deletes the old allocation
 Any other pointer to the data should be correctly
changed by the programmer
 void *realloc(void *ptr, size_t newSize);
 ptr=(int *) realloc (ptr ,15*sizeof(int));
31
Smitha N Pai 7/24/2019
Releasing memory (free)
 Memory allocated using malloc, calloc and realloc
is released using free
 It is an error to free memory with a null pointer, a
pointer to other than the first element of an
allocated block or to refer to memory after it has
been released
 void free(void *ptr);
 It is not the pointer that is released but what they
point to.

32
Smitha N Pai 7/24/2019
free (contd.)
 To release an array of memory that was allocated
using calloc, release the pointer once
 It is an error to release each element individually

 Releasing memory does not change the value in a


pointer- it contains address in the heap
 Free the memory whenever it is no longer needed –
need not be at the end of the program
 OS releases memory when the program terminates

33
Smitha N Pai 7/24/2019
free (contd.)
 It is a logic error to use the pointer after memory
has been released
 Program could continue to run but data may be
destroyed if the memory area is allocated for another
use
 Logic error difficult to trace

 Hence, clear the pointer by setting to NULL


immediately after freeing memory

34
Smitha N Pai 7/24/2019
Array of pointers
 It is helpful when the size of the data in the array is
variable- ragged array
 The right elements in each row may be empty,
giving it an uneven right border
 Using 2D array we are wasting lot of memory –
Solution create many one-D arrays that are joined
through an array of pointers
 int**table;
 table = (int **)calloc(rowNum +1, sizeof(int *));

35
Smitha N Pai 7/24/2019

Você também pode gostar