OOP 2012 - Hint: Dynamic allocation in c++
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

OOP 2012 - Hint: Dynamic allocation in c++

on

  • 765 views

 

Statistics

Views

Total Views
765
Views on SlideShare
765
Embed Views
0

Actions

Likes
0
Downloads
16
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

OOP 2012 - Hint: Dynamic allocation in c++ Presentation Transcript

  • 1. Dynamic Allocation in C++allan914.120418 (update: 120420)
  • 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. Example 1: ResultSample Input10 Sample Output1 2 3 4 5 6 7 8 9 10
  • 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. Example 2: Result Sample Input54Sample Output12342345345645675678
  • 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. Example 3: Result Sample Input54Sample Output12342345345645675678
  • 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. Example 4: Result Sample Input54Sample Output12342345345645675678
  • 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. Example 5: Result Sample Input54Sample Output12342345345645675678