Pointer applications To understand the relationship between arrays and pointers. To understand the design and concepts behind pointer arithmatic. To write.

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Programming and Data Structure
Dynamic Memory Allocation
CS1061: C Programming Lecture 21: Dynamic Memory Allocation and Variations on struct A. O’Riordan, 2004, 2007 updated.
ECE Application Programming Instructor: Dr. Michael Geiger Fall 2012 Lecture 31: Dynamic memory allocation.
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
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.
Introduction of Memory Allocation. Memory Allocation There are two types of memory allocations possible in c. Compile-time or Static allocation Run-time.
Kernighan/Ritchie: Kelley/Pohl:
Memory Allocation. Memory A memory or store is required in a computer to store programs (or information or data). Data used by the variables in a program.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Discussion: Week 3/26. Structs: Used to hold associated data together Used to group together different types of variables under the same name struct Telephone{
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Dynamic memory allocation. The process of allocating memory at run time is known as dynamic memory allocation. C have four library functions for allocating.
1 Day 03 Introduction to C. 2 Memory layout and addresses r s int x = 5, y = 10; float f = 12.5, g = 9.8; char c = ‘r’, d = ‘s’;
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Pointers Applications
Introduction to Pointers.. What is a pointer? A derived type which holds the address of a variable. Simply a memory location where the variable is stored.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
C Programming Day 4. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 More on Pointers Constant Pointers Two ways to.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Pointers in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Memory and Addresses Memory is just a sequence of byte-sized.
ECE Application Programming
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
ECE Application Programming Instructors: Dr. Michael Geiger & Nasibeh Nasiri Fall 2015 Lecture 31: Structures (cont.) Dynamic memory allocation.
1 Dynamic Memory Allocation. 2 In everything we have done so far, our variables have been declared at compile time. In these slides, we will see how to.
ENEE150 – 0102 ANDREW GOFFIN Dynamic Memory. Dynamic vs Static Allocation Dynamic  On the heap  Amount of memory chosen at runtime  Can change allocated.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Stack and Heap Memory Stack resident variables include:
Day 03 Introduction to C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Day 03 Introduction to C.
Programming and Data Structures
Pointers and dynamic memory
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
CS111 Computer Programming
Memory Allocation CS 217.
Dynamic Memory Allocation
EECE.2160 ECE Application Programming
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
CS111 Computer Programming
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Dynamic Memory – A Review
EECE.2160 ECE Application Programming
Presentation transcript:

Pointer applications To understand the relationship between arrays and pointers. To understand the design and concepts behind pointer arithmatic. To write programs using arrays and pointer arithmetic. To understand passing arrays to functions. To understand dynamic memory allocation. To write programs using static and dynamic memory allocation.

Pointer Applications Arrays and pointers: Arrays and pointers have close relationship. Array is a collection of similar elements stored in contigous memory locations. Hence pointers can be easily applied on arrays. void main() { int a[5]={1,2,3,4,5}; int i=0; while(i<5) { printf(address of element %d is %p”,i, &a[i]); }

Pointer applications The name of an array is the pointer constant to the first element. int a[]={1,2,3,4}; a and &a[0] both are same We can use the array name anywhere we use the pointer as long as it is being used as an rvalue. printf(“%p %p”,&a[0],a);

Pointer applications Printing first element *a same as a[0] Store a in a pointer variable int a[4]={1,2,3,4}; int *p=a; printf(“%d%d”,*p,*a); Multiple pointer to arrays int a[3]={1,2,3}; int *p=&a[1]; printf(“%d %d %d”,a[0],p[-1],p[0]);

Pointer arithmetic and arrays a is a pointer to a[0] a+1 is a pointer to a[1] a+2 is a pointer to a[2] and so on Address=pointer+offset*size of element Pointer arithmetic on different types Dereferencing array pointers a[2] is same as *(a+2)

Two methods to access the elements of array: 1.using subscript. 2.Using pointers. Subscript method: void main() { int a[5]={1,2,3,4,5}; int i=0; while(i<5) { printf(address of element %d is %p”,a[i], &a[i]); i++; }

Pointer method: Pointers can be made to point to the array and then used to access the elements. Efficient method in complex situations. Main() { int a[3]={1,2,3}; int *ptr; int i=0; ptr=&a[0]; while(i<3) { printf(element is %d, *ptr); ptr++; i++; }

Base address of an array: Starting address of an array. Represented by the ‘&array_name[0]’(ex:&a[0]). Can also represented by just specifying the array name.(ex:a) int a[3]; int *ptr; ptr=&a[0];//also ptr=a; Here if array starts at address 2000, then ptr will have value Since array name gives its starting address, *a gives the first element of the array. Pointers can also be used array name and index it to point to different elements in the array. print(ptr[0]);//prints first element of array a print(ptr[2]);//prints 3 rd element of a

Pointer arithmetic and arrays: Pointers pointing to array can be 1.Incremented or decremented. 2.An integer can be added to pointer. 3.An integer can be subtracted from the pointer. 4.Two pointers pointing to the same array can be subtracted. 5. Pointers can be compared using relational operators(array) void main() { int a[3]={1,2,3}; int *ptr; int i=0; ptr=a; while(i<3) { printf(element is %d, *ptr); ptr++; i++; }}

o/p:1 2 3 void main() { int a[3]={1,2,3}; int *ptr; int i=3; ptr=&a[2]; //ptr=a+2; while(i>=0) { printf(element is %d, *ptr); ptr--; i--; } o/p: 3 2 1

Main() { int a[7]={1,2,3,4,5,6,7}; int *ptr; ptr=a; printf(“element at zero position is %d”, *ptr);//1 ptr=ptr+3; printf(“element at 3 rd position is %d”, *ptr);//4 ptr=ptr+2; printf(“element at 5 th position is %d”, *ptr);//6 ptr=ptr-3; printf(“element at 2 nd position is %d”, *ptr);//3 }

Array name can also be used to increment or decrement. int a[4]={1,2,3,4}; print(*a);//1 print(*(a+1));//2 print(*(a+3));//4 Addition of 2 pointers is not allowed but subtraction is possible only if the pointers points to the same array. Subtraction of 2 pointers gives the number of elements between 2 pointers. int a[4]={1,2,3,4}; int *ptr1,*ptr2; ptr1=a; ptr2=&a[2];//or ptr2=a+2 k=ptr2-ptr1;//2

Find the smallest in an array #define SIZE 10 void main() { int a[SIZE]={21,31,4,51,63,78,80,19,10,11}; int *psm,*plast,*pwalk; plast=a+SIZE-1; psm=a; pwalk=a+1; while(pwalk<=plast) { If (*psm>*pwalk) psm=pwalk; pwalk++; }

Binary search int bsearch(int list[],int *endp,int target,int **locp) { int *fp,*mp,*lp; fp=list; lp=endp; while(fp<=lp) { mp=fp+(lp-fp)/2; if(target>*mp) fp=mp+1; else if(target<*mp) lp=mp-1;

Binary search else break; } *locp=mp; return (target==*mp);} void main() { int list[10]={12,34,56,64,68,70,79,88,99,100}; int found,int *pos=NULL; int key;

Binary search printf(“Enter key”); scanf(“%d”,&key); found=bsearch(list,list+9,key,&pos); If(found) printf(“Key is found and its position is%d”, *pos); else printf(“key is not found”); }

Pointers and 2D-arrays 2D array is an array of 1D arrays. A[2][3]; is nothing but two 1D arrays of 3 elements each. a[2][3]={1,2,3,4,5,6}; will be stored in memory locations as shown below a[0] gives the base address of 0 th 1D array and a[1] gives the base address of 1 st first 1D array. hence a[0]  2000 and a[1]  a[1] a[0]

In 1D array ‘*’ prefixed with array name gives the element at that position in array. i.e *a  1//also *(a+0) *(a+1)  2 etc Since 2D arrays are collection of 1D arrays,‘*’ prefixed with 2D array name gives the base address of 1D array. a[2][3]; *(a+0)  2000 *(a+1)  2006 How to refer to individual elements of 2D array using pointers? for ex: how is a[1][2] element represented using pointers. a[1] is represented as *(a+1). Now, a[1][2] is nothing but the 3 rd element of the row that we reached in the previous step. hence it can be represented as *(*(a+1)+2)

a[2][3]={1,2,3,4,5,6}; *(a+0) *(a+1) *(a+1)+2 *(*(a+1)+2)  6 Hence element a[2][1] can be written as *(*(a+2)+1); and a[1][1] as *(*(a+1)+1) and so on. In general element a[i][j] can be written as *(*(a+i)+j);

Passing array to functions: Array can be passed to functions by 1.Passing value of array elements. 2.Passing address of array elements to functions. 3.Passing the base address of the array. Passing value of array elements: Main() { int arr[3]={1,2,3}; for(i=0;i<3;i++) display(arr[i]); }

Void display(int m) { print(m); } o/p: Changes not reflected in actual arguments. Passing address of array elements: Main() { int arr[3]={1,2,3}; for(i=0;i<3;i++) display(&arr[i]); }

Void display(int *ptr) { print(*ptr); } o/p : Passing the base address: Main() { int arr[3]={1,2,3}; display(arr,3); }

Void display(int *ptr, int n) { int i; for(i=0;i<n;i++) { printf(“%d”,*ptr);//also ptr[i] ptr++; } o/p : It is compulsory to pass the number of elements to the function display because display function does not know the size of array.

Array of pointers: Is nothing but an array which contains addresses. Main() { int *arr[4];//array of pointers int i=1,j=2,k=3,l=4; arr[0]=&i; arr[1]=&j; arr[2]=&k; arr[3]=&l; for(m=0;m<4;m++) printf(“%d”,*(arr[m]) ); } o/p:

Memory management Memory is divided into program memory and data memory Program memory memory used for functions and main Data memory is divided into global,stack and heap memory Global memory holds global data of program Stack memory holds local variables with respect to different activations of the functions Heap memory is unused memory allocated to the program and available to be assigned during program execution.

Memory allocation functions: There are 2 types of memory allocations 1.Static allocation (inefficient) 2.Dynamic allocation(efficient) Static allocation: Happens during compile time. Memory once allocated is fixed. Results in wastage or shortage of memory. Use of arrays is static allocation.

Main() { int arr[50]; printf(“enter the no of elements”); scanf(“%d”&n); printf(“enter employee ID’s); for(i=0;i<n;i++) scanf(“%d”, &arr[i]); } An array is created with capacity to hold upto 50 integers. The size of 50 is fixed and cannot be changed. Now if number of employees is 25, remaining 25 spaces will get wasted. Now if you want to enter more than 50 emp ID’s, array memory will fall short. These are disadvantages of the static allocation. To overcome these we use dynamic allocation.

Dynamic allocation: Allocating memory during runtime of the program. Memory is allocated only as much is really required, not a byte more and not a byte less. It is done by using pointers. There are 3 functions in c for dynamic allocation 1.Malloc 2.Calloc 3.Realloc One for freeing the memory allocation 1. Free These functions are present in the header file.

malloc void *malloc(size_t size); size_t is a datatype defined in stdio.h as unsigned integer which can hold the maximum address of the computer. Ex: int *ptr=(int*)malloc(sizeof(int)); Returns a pointer to the first byte of a block of memory whose size is size and contents are uninitialized. Returns NULL if unsuccessful. If size==0 then result is unpredictable.

Usage If(ptr=(int *)malloc(sizeof(int))) exit(100);

Calloc Used for arrays. Void * calloc(size_t count,size_t elementsize); Allocates count*elementsize number of bytes and returns start address. Initializes block content to null char. Returns NULL if unsuccessful int *a=(int *)calloc(10,sizeof(int)); if(!ptr=(int*)calloc(200,sizeof(int))) exit (100);

Realloc Whenever allocated block needs to be extended or shrinked we use realloc. Void * realloc(void *ptr,size_t newsize)); If extension is not possible at old place it allocates the block at new place,copies contents of old place,delets old place and returns pointer to new place.

Free Void free(void * ptr); Free(NULL) free(a pointer to other than first byte),free(different datatype ptr) not allowed. Free(ptrname);

Main() { int n,*ptr,i; printf(“enter the no of employees”); scanf(“%d”&n); ptr=(int *)malloc(n * Sizeof(int));//dynamic allocation if(ptr==NULL) { printf(“insufficient memory”); exit(); } printf(“enter employee ID’s); for(i=0;i<n;i++) scanf(“%d”, (ptr+i)); printf(“displaying emp ID’s”); for(i=0;i<n; i++) printf(“%d”, *(ptr+i)); }

Close look at ptr=(int *) malloc (n * sizeof(int)); Here if n is 5, then 5* sizeof(int) i.e 5*2 = 10 bytes are allocated which is exactly what is required for storing 10 employee ID’s, not a single byte less or more ptr Since we have to store emp ID’s which is an int, int is specified as the parameter of sizeof() function. Malloc function always returns a void pointer. It has to be typecasted to int pointer since ptr is pointing to int type emp ID Malloc function returns a pointer which points to the first byte of the block of memory allocated.

Calloc: It is same as malloc, but here it takes 2 parameters. calloc (int m, int n); m indicates number of blocks. n indicates size of each block. Ex: int *ptr; ptr=(int *) calloc (5, sizeof(int)); This reserves space of 10 bytes.i.e 5 blocks of size 2 each. Realloc: Used to change the size of memory already allocated, using malloc or calloc. It is rarely used.

If sufficient amount of memory is not there, malloc returns NULL. (ptr+i) in scanf specifies the address where ID is to be stored Ptr Ptr+1 Ptr+2

ptr=(int *) realloc (ptr, 10 * sizeof(int)); Initially ptr was pointing to a block of bytes(10 bytes) allocated by malloc. After the above statement is executed, size of memory is increased to 20 bytes and ptr points to first byte. If the extra memory is not available in a full stretch, then entire block starting from first byte is shifted to some other location and new address of first byte is returned to ptr. Freeing memory: Memory allocated using malloc,calloc or realloc must be freed at the end of program or else this memory cannot be used by other programs. Freeing is done free() function. Ex: free(ptr);

Array of pointers Ragged array Ex:

Array of pointers int **table=(int **)calloc(5,sizeof(int*)); table[0]= (int *)calloc(4,sizeof(int)); table[1]= (int *)calloc(7,sizeof(int)); table[2]= (int *)calloc(1,sizeof(int)); table[3]= (int *)calloc(3,sizeof(int)); table[4]= (int *)calloc(2,sizeof(int));

1.Write a program to create,fill and print a table. 2. For the above program add functions which compute rowmax,rowmin,rowaverage for each row.