150 likes | 272 Views
Dynamic Memory. Static v.s. dynamic memory. Stataic memory, for example: int x; double y[100]; is allocated and de allocated implicitly. Dynamic memory is allocated and de allocated during execution explicitly using new and delete statements. new statement.
E N D
Static v.s. dynamic memory • Stataic memory, for example: int x; double y[100]; is allocated and de allocated implicitly. • Dynamic memory is allocated and de allocated during execution explicitly using new and delete statements.
new statement The new statement is used to allocate memory during run-time. Example: int *p; p=new int; // returns the address of allocated 2 bytes. If // memory could not be allocated NULL is // returned. cin>>*p; cout>>*p;
Example double * B=new double[20]; // B is a dynamic array of 20 // double elements. B points to //the first element. int N; int *A; cin>>N; A=new int[N]; // A is a dynamic array of N integers
delete statement • The delete statement is used to de allocate memory reserved during run-time using new statement. • Example: char *p=new char; cin>>*p; … delete p;
Example int *a; a=new int[10]; for (int i=0; i<=9; i++) cin>>a[i]; // cin>>*(a+i); … delete a; // deletes only a[0] delete [ ] a;// deletes the 10 elements
Example: dynamic array to store a string char *s; s=new char[20]; cin>>s; cout<<s; cin>>*s; cin>>*(s+1); cout<<s[3];
Example: a list of 20 names each of which stored in a dynamic array char *A[20]; for(i=0; i<=19; i++){ cin>>A[i]; // error A[i]=new char[40]; cin>>A[i]; cout>>A[i]; } … for(i=0; i<=19; i++) delete [ ]A[i];
Example: a list of N names each of which stored in a dynamic array char **A; int N; cin>>N; A=new char*A[N]; for(i=0; i<=N-1; i++){ A[i]=new char[40]; cin>>A[i]; } … for(i=0; i<=N-1; i++) delete [ ]A[i];
Example: 10x10 dynamic matrix of integers int * a[10]; for(i=0;i<=9;i++) a[i]=new int[10];
Example: mxn dynamic matrix of integers int **b; int m,n; cin>>m>>n; b=new int *[m]; for(i=0;i<=m-1;i++) b[i]=new int[n]; … //read values for(i=0;i<=m-1;i++) for(i=0;i<=n-1;i++) cin>>b[i][j]; //cin>>*(*(b+i)+j); //delete dynamic memory for(int i=0; i<=m;i++) delete [ ]b[i]; delete[ ]b;
Example: dynamic array of dynamic strings char **b; char s[80]; int m;//number of strings cin>>m; b=new char*[m]; for(int i=0; i<m; i++){ cin>>s; b[i]=new char[strlen(s)+1]; strcpy(b[i],s); }
Exercize • Write a function that takes an array called X of N integers and returns a pointer to a new array that has the original vales of X stored in ascending order. Do not change the values of X. • Redo using pass by reference.
Exercize • Write a function to find the min and max in a matrix and store the results in a dynamic one-dimensional array of 2 elements and return the address of the dynamic memory. • Redo using pass by reference.
Exercize • Write a function to count and store the even values in an array in a dynamic array and returns the address of this array. • Redo using pass by reference.