# pointer applications

Post on 30-Dec-2015

14 views

Category:

## Documents

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

TRANSCRIPT

• Pointer applications

• Arrays and pointersName of an array is a pointer constant to the first element whose value cannot be changedAddress and name refer to the same location in the memory which is inter-changable provided it is used as rvalueDereferencing 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 timemain(){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 arraysPointer arithmetic offers restricted set of arithmetic operations for manipulating the addresses in pointersUseful 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 pointerPointers of different types cannot be assigned to one anotherAddress=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 operatorsOperation on pointersAddition of pointer and integer, pointer and pointerSubtraction is only between two pointers or first is a pointer and the second is an integerPointers can have postfix and unary operatorsResult 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

• Examplesp+55+pp-5p1-p2p++--pp1>=p2p1!=p2if (ptr ==NULL) same as if (!ptr)if (ptr!=NULL) is same as if(ptr)

• Pointers and two dimensional arraysName of the array is a pointer constant to the first element of the array which is another arrayDereferencing array name, we get another pointer to one dimensional arraytable[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 rowGiven pointer to a row, dereference the row pointer to get individual elementDouble reference is given as *(*(table)) table[i][j] is identical to *(*(table +i) +j)

• Passing an array to a functionArray name itself is a pointer constant which is the address of the first element in the arrayArray notation to declare/define an array in the functionint func(int arr[]) { }Using pointersint func(int *p) { }For multidimensional use the array syntax in the header declaration and definition float func(int bigarr[][4][5])

• Understanding complex declaraions6 4 2 Start here 1 3 5int x ; x is # an integerint x #2 0 1int * p # # ; p is #a pointer #to an integerint table [4] ; table is an array of 4 integersint table [4][5] ; table is an array [4][5]of integersint * arrofptr[5] # ;arrofptr is an array of 5 pointers to #integerIdentifier

• int (*ptrarr # ) [5] ; prtarry is a pointer # to an array of 5 integersint func() ; func is a function returning an integerint * func(int ) # ; func is a function returning a pointer to an integerUnderstanding complex declaraions

• Memory allocation functionsStatic and dynamicStatic memory allocation Declaration and definition of memory fully specified in source programNumber of bytes reserved cannot be changed during run timeShould know exactly what is the data requirement

• Memory allocation functions(contd)Dynamic memory allocation- Memory allocation at executionUses predefined functions to allocate and release memory for data while program is runningPostpones the data definition to run timeProgrammer must use either standard data types or must have declared any derived data type

• Memory usageMemory management functions used with dynamic memoryMemory management functions -malloc, calloc, realloc for memory allocation and free to return memory not in use - in standard library header file Memory = Program memory+ data memoryProgram memory = main + called functionsData memory = permanent definitions (global data and constants) + local definitions + dynamic data memory

• Main is memory all the timeEach 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 runningProgram code for function is in memory at all timesLocal variable is available only when it is activeMemory usage(contd.)

• More than one version of the function can be active at a timeIf multiple copies of local variable are allocated although only one copy of the function is presentMemory facility for this capability is stackHeap is unused memory allocated to the program and available to be assigned during its executionIt is a memory pool from which memory is allocated when requested by the memory allocation functionsMemory usage(contd.)

• Memory Allocation ( malloc)Allocates a block of memory that contains the number of bytes specified in its parameterReturns void pointer to the first byte of the allocated memoryAllocated memory is not initialized contains garbagevoid *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 computere.g. pint = (int *) malloc (sizeof (int));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 usedMemory is allocated in the heap only through a pointer and does not have its own identifierAttempting to allocate a size zero memory- results unpredictable could return NULL or implementation dependant valueif (!ptr =(int *) malloc (sizeof(int)))) exit (100);malloc (contd.)

• Contiguous memory allocation -calloc Used to allocate memory for arraysIt allocates contiguous block of memory large enough to contain an array of elements of a specified sizeIt returns a pointer to the first element of the allocated arrayThe size associated with its pointer is the size of one element not the entire arrayIt clears the memory- the memory it allocates is set to zeroZero 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.)Prototypevoid * calloc(size_t element-count, size_t element-size);e.g.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 blockIf 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 allocationAny other pointer to the data should be correctly changed by the programmervoid *realloc(void *ptr, size_t newSize);ptr=(int *) realloc (ptr ,15*sizeof(int));

• Releasing memory (free)Memory allocated using malloc, calloc and realloc is released using freeIt 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 releasedvoid 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 onceIt is an error to release each element individuallyReleasing memory does not change the value in a pointer- it contains address in the heapFree the memory whenever it is no longer needed need not be at the end of the programOS releases memory when the program terminates

• 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 useLogic error difficult to traceHence, clear the pointer by setting to NULL immediately after freeing memory

• Array of pointersIt is helpful when the size of the data in the array is variable- ragged arrayThe right elements in each row may be empty, giving it an uneven right borderUsing 2D array we are wasting lot of memory Solution create many one-D arrays that are joined through an array of pointersint **table;table = (int **)calloc(rowNum +1, sizeof(int *));

**************************