SlideShare una empresa de Scribd logo
1 de 11
Descargar para leer sin conexión
Dynamic Allocation in C++
allan914.120418 (update: 120420)
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;
}
Example 1: Result
Sample Input
10

 Sample Output
1 2 3 4 5 6 7 8 9 10
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;
}
Example 2: Result
   Sample Input
5
4
Sample Output
1234
2345
3456
4567
5678
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;
}
Example 3: Result
   Sample Input
5
4
Sample Output
1234
2345
3456
4567
5678
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;
}
Example 4: Result
   Sample Input
5
4
Sample Output
1234
2345
3456
4567
5678
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;
}
Example 5: Result
   Sample Input
5
4
Sample Output
1234
2345
3456
4567
5678

Más contenido relacionado

La actualidad más candente

Programa.eje
Programa.ejePrograma.eje
Programa.eje
guapi387
 
Static Variable in C++
Static Variable in C++Static Variable in C++
Static Variable in C++
Nasir Hamidon
 
Class array
Class arrayClass array
Class array
nky92
 

La actualidad más candente (20)

C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Programa.eje
Programa.ejePrograma.eje
Programa.eje
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
C++ TUTORIAL 9
C++ TUTORIAL 9C++ TUTORIAL 9
C++ TUTORIAL 9
 
Static Variable in C++
Static Variable in C++Static Variable in C++
Static Variable in C++
 
Class array
Class arrayClass array
Class array
 
Oop lab report
Oop lab reportOop lab report
Oop lab report
 
1
11
1
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
Permute
PermutePermute
Permute
 
C questions
C questionsC questions
C questions
 
Permute
PermutePermute
Permute
 
Tugas struktur data terakhir_pohonBiner
Tugas struktur data terakhir_pohonBinerTugas struktur data terakhir_pohonBiner
Tugas struktur data terakhir_pohonBiner
 
Doubly linklist
Doubly linklistDoubly linklist
Doubly linklist
 
Extending built in objects
Extending built in objectsExtending built in objects
Extending built in objects
 
Lo17
Lo17Lo17
Lo17
 
Boundary Fill Algorithm in C
Boundary Fill Algorithm in CBoundary Fill Algorithm in C
Boundary Fill Algorithm in C
 
Function basics
Function basicsFunction basics
Function basics
 
Rumus VB-2
Rumus VB-2Rumus VB-2
Rumus VB-2
 

Destacado

мероприятия
мероприятиямероприятия
мероприятия
ElenaSam
 
выпуск 7
выпуск 7выпуск 7
выпуск 7
ElenaSam
 
здоровый образ жизни
здоровый  образ жизниздоровый  образ жизни
здоровый образ жизни
ElenaSam
 
Latihan reproduction
Latihan reproductionLatihan reproduction
Latihan reproduction
ruziana1986
 
урок мужества
урок мужестваурок мужества
урок мужества
ElenaSam
 
Черепанова и Малыхина
Черепанова и МалыхинаЧерепанова и Малыхина
Черепанова и Малыхина
ElenaSam
 
итоги педсовет
итоги педсоветитоги педсовет
итоги педсовет
ElenaSam
 
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
Kostas Mavridis
 
зарница
зарницазарница
зарница
ElenaSam
 
итоги чемпионат2013
итоги чемпионат2013итоги чемпионат2013
итоги чемпионат2013
ElenaSam
 

Destacado (20)

Replastificacion
ReplastificacionReplastificacion
Replastificacion
 
Креатив в действии: конверсия в результат
Креатив в действии: конверсия в результатКреатив в действии: конверсия в результат
Креатив в действии: конверсия в результат
 
Автоматизация емейл-маркетинга: от простого к сложному
Автоматизация емейл-маркетинга: от простого к сложномуАвтоматизация емейл-маркетинга: от простого к сложному
Автоматизация емейл-маркетинга: от простого к сложному
 
квн
квнквн
квн
 
соко
сокосоко
соко
 
Как запустить емейл маркетинг в кратчайшие сроки
Как запустить емейл маркетинг в кратчайшие срокиКак запустить емейл маркетинг в кратчайшие сроки
Как запустить емейл маркетинг в кратчайшие сроки
 
мероприятия
мероприятиямероприятия
мероприятия
 
Емейл-маркетинг: как поднять целину
Емейл-маркетинг: как поднять целинуЕмейл-маркетинг: как поднять целину
Емейл-маркетинг: как поднять целину
 
выпуск 7
выпуск 7выпуск 7
выпуск 7
 
здоровый образ жизни
здоровый  образ жизниздоровый  образ жизни
здоровый образ жизни
 
Latihan reproduction
Latihan reproductionLatihan reproduction
Latihan reproduction
 
урок мужества
урок мужестваурок мужества
урок мужества
 
Черепанова и Малыхина
Черепанова и МалыхинаЧерепанова и Малыхина
Черепанова и Малыхина
 
итоги педсовет
итоги педсоветитоги педсовет
итоги педсовет
 
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
EoinWoods_WhereDidMyArchitectureGoPreservingSoftwareArchitectureInItsImplemen...
 
Hayashi masw gravity
Hayashi masw gravityHayashi masw gravity
Hayashi masw gravity
 
зарница
зарницазарница
зарница
 
Friends
Friends Friends
Friends
 
итоги чемпионат2013
итоги чемпионат2013итоги чемпионат2013
итоги чемпионат2013
 
Presentation3
Presentation3Presentation3
Presentation3
 

Similar a OOP 2012 - Hint: Dynamic allocation in c++

Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
Jeff Tu Pechito
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
HIMANSUKUMAR12
 
Lab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practiceLab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practice
ranaibrahim453
 

Similar a OOP 2012 - Hint: Dynamic allocation in c++ (20)

C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd Study
 
ماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارام
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
 
oodp elab.pdf
oodp elab.pdfoodp elab.pdf
oodp elab.pdf
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
Notes for C++ Programming / Object Oriented C++ Programming for MCA, BCA and ...
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)
 
Cpp c++ 1
Cpp c++ 1Cpp c++ 1
Cpp c++ 1
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
Arrays
ArraysArrays
Arrays
 
array2d.ppt
array2d.pptarray2d.ppt
array2d.ppt
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
Lab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practiceLab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practice
 

Último

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

OOP 2012 - Hint: Dynamic allocation in c++

  • 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 Input 10  Sample Output 1 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 Input 5 4 Sample Output 1234 2345 3456 4567 5678
  • 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 Input 5 4 Sample Output 1234 2345 3456 4567 5678
  • 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 Input 5 4 Sample Output 1234 2345 3456 4567 5678
  • 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 Input 5 4 Sample Output 1234 2345 3456 4567 5678