26
Pointer applications

Pointer applications

Embed Size (px)

DESCRIPTION

Pointer applications. 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 - PowerPoint PPT Presentation

Citation preview

Pointer applications

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]

• ais same as &a[0] where a is the pointer to the first element and not the whole array

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;

}

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;

}

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

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

Pointer and one dimensional arrays

Pointers and other operators• Operation on pointers

o Addition of pointer and integer, pointer and pointero Subtraction is only between two pointers or first is a

pointer and the second is an integero Pointers can have postfix and unary operatorso Result of subtraction is an index representing the number

of elements between two pointers-Meaningful if two pointers are associated with same array structure.

o Relational operators are allowed only if both operands are pointers of the same type

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)

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)

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

functiono int func(int arr[]) { }

• Using pointerso int func(int *p) { }

• For multidimensional use the array syntax in the header declaration and definition o float func(int bigarr[][4][5])

Understanding complex declaraions6 4 2 Start here 1 3 5

• int x ; “x is # an integer”o int x #o 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 [4][5]of integers”• int * arrofptr[5] # ;arrofptr is an array of 5 pointers to #

integer

Identifier

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

Understanding complex declaraions

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

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

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

• 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

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

Memory usage(contd.)

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

garbageo 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

o e.g. pint = (int *) malloc (sizeof (int));

o malloc returns the address of the first byte in the memory space allocated on success or NULL otherwise

• 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 valueo if (!ptr =(int *) malloc (sizeof(int)))) exit (100);

malloc (contd.)

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

Calloc (contd.)• Prototype

o void * calloc(size_t element-count, size_t element-size);• e.g.

o if (!ptr=(int *)calloc(200,sizeof(int)))) exit(100);

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 programmero void *realloc(void *ptr, size_t newSize);o ptr=(int *) realloc (ptr ,15*sizeof(int));

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 releasedo void free(void *ptr);

• It is not the pointer that is released but what they point to.

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

free (contd.)• It is a logic error to use the pointer after memory has

been released o Program could continue to run but data may be destroyed

if the memory area is allocated for another useo Logic error difficult to traceo Hence, clear the pointer by setting to NULL immediately

after freeing memory

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 pointerso int **table;o table = (int **)calloc(rowNum +1, sizeof(int *));