Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations

Presentation on theme: "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."— Presentation transcript:

1 Pointer applications

2 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

3 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; }

4 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; }

5 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

6 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

7 Pointers and other operators Operation on pointers o Addition of pointer and integer, pointer and pointer o Subtraction is only between two pointers or first is a pointer and the second is an integer o Pointers can have postfix and unary operators o 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

8 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)

9 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)

10 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 o int func(int arr[]) { } Using pointers o int func(int *p) { } For multidimensional use the array syntax in the header declaration and definition o float func(int bigarr[][4][5])

11 Understanding complex declaraions 6 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

12 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

13 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

14 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

15 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 Memory = Program memory+ data memory Program memory = main + called functions Data memory = permanent definitions (global data and constants) + local definitions + dynamic data memory

16 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.)

17 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.)

18 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 o 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

19 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 o if (!ptr =(int *) malloc (sizeof(int)))) exit (100); malloc (contd.)

20 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

21 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);

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

23 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 o void free(void *ptr); It is not the pointer that is released but what they point to.

24 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

25 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 use o Logic error difficult to trace o Hence, clear the pointer by setting to NULL immediately after freeing memory

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

Download ppt "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."

Similar presentations

Ads by Google