Upcoming SlideShare
×

# OOP 2012 - Hint: Dynamic allocation in c++

936 views

Published on

Published in: Technology, Spiritual
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

### OOP 2012 - Hint: Dynamic allocation in c++

1. 1. Dynamic Allocation in C++allan914.120418 (update: 120420)
2. 2. Example 1#include<iostream>using namespace std;int main(){ int* a; int n; cin >> n; a=new int [n]; for(int i=0;i<n;i++) a[i]=i+1; for(int i=0;i<n;i++) cout << a[i] << " "; delete [] a; return 0;}
3. 3. Example 1: ResultSample Input10 Sample Output1 2 3 4 5 6 7 8 9 10
4. 4. Example 2#include<iostream>using namespace std;int main() { int** a; int n,m; cin >> n; cin >> m; a=new int* [n]; for(int i=0;i<n;i++) a[i]=new int [m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=i+j+1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) cout << a[i][j] << " "; cout << endl; } for(int i=0;i<n;i++) delete [] a[i]; delete [] a; return 0;}
5. 5. Example 2: Result Sample Input54Sample Output12342345345645675678
6. 6. Example 3#include<iostream>using namespace std;int main() { int* a; int n,m; cin >> n; cin >> m; a=new int [n*m]; int** b; b=new int* [n]; for(int i=0;i<n;i++) b[i]=&(a[n*i]); for(int i=0;i<n;i++) for(int j=0;j<m;j++) b[i][j]=i+j+1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) cout << b[i][j] << " ";//cautious with CodeBlocks ! cout << endl; } delete [] b; delete [] a; return 0;}
7. 7. Example 3: Result Sample Input54Sample Output12342345345645675678
8. 8. Example 4// Headers emitted, cautious with CodeBlocks !void* new2d(int n,int m,int size) { void **a = new void* [m*sizeof(void*) + n*m*size]; for(int j=0;j<m;j++) a[j] = ((char *)(a+m)) + j*n*size; return a;}int main() { int** a; int n,m; cin >> n; cin >> m; a = (int**)new2d(n,n,sizeof(int)); for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=i+j+1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) cout << a[i][j] << " "; cout << endl; } delete [] a; return 0;}
9. 9. Example 4: Result Sample Input54Sample Output12342345345645675678
10. 10. Example 5#include<iostream>#include<vector>using namespace std;int main() { int n,m; cin >> n; cin >> m; vector<vector<int> > a(n, vector<int>(m)); for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=i+j+1; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) cout << a[i][j] << " "; cout << endl; } return 0;}
11. 11. Example 5: Result Sample Input54Sample Output12342345345645675678