SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados (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
 

Destaque

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

Destaque (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
 

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

C++ Programming - 2nd Study
C++ Programming - 2nd StudyC++ Programming - 2nd Study
C++ Programming - 2nd StudyChris Ohk
 
ماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامماترێکس به‌ کوردی ئارام
ماترێکس به‌ کوردی ئارامAram Jamal
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
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 BoFTimur Safin
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacionJeff Tu Pechito
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
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 ...ssuserd6b1fd
 
Introduction to cpp (c++)
Introduction to cpp (c++)Introduction to cpp (c++)
Introduction to cpp (c++)Arun Umrao
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfHIMANSUKUMAR12
 
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-ee01083101premrings
 

Semelhante 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
 
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
 
Final DAA_prints.pdf
Final DAA_prints.pdfFinal DAA_prints.pdf
Final DAA_prints.pdf
 
7720
77207720
7720
 

Último

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Último (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

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