Está en la página 1de 3

Program ilustrativ

matrice cu dimensiunui variabile

#include<iostream>
using namespace std;

//matrice de tip nrLin x 100

typedef int Linie[100];
Linie* aloca1(int nrLin){
//alocam dinamic un tablou de linii
return new Linie[nrLin];
}
void dealoca1(Linie* p){
delete [] p;
}
void exemplul1(){
cout<<"Exemplul 1\n"<<endl;
int nrLin=3, nrCol=7;
//alocam static pointerul cap de tablou de linii
Linie* tab;
//incarcam in tab adresa primei linii
tab=aloca1(nrLin);
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
tab[i][j]=i+j;
}
}
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
cout<<tab[i][j]<<' ';
}
cout<<endl;
}
cout<<endl;
dealoca1(tab);
}

//matrice de tip 100 x nrCol

void aloca2(int* tab[100], int nrCol){
//incarcam pointerii cap de linie
for(int i=0; i<100; i++)
tab[i]=new int[nrCol];
}
void dealoca2(int* tab[100]){
for(int i=0; i<100; i++)
delete [] tab[i];
}

void exemplul2(){
cout<<"Exemplul 2\n"<<endl;
int nrLin=3, nrCol=7;
//alocam static coloana pointerilor cap de linie
int* tab[100];
//incarcam in tab pointerii cap de linie
aloca2(tab,nrCol);
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
tab[i][j]=i+j;
}
}
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
cout<<tab[i][j]<<' ';
}
cout<<endl;
}
cout<<endl;
dealoca2(tab);
}

//matrice de tip nrLin x nrCol

int** aloca3(int nrLin, int nrCol){
//alocam dinamic coloana pointerilor cap de linie
int** p=new int*[nrLin];
//incarcam pointerii cap de linie
for(int i=0; i<nrLin; i++)
p[i]=new int[nrCol];
return p;
}
void dealoca3(int ** p, int nrLin){
for(int i=0; i<nrLin; i++)
delete [] p[i];
delete [] p;
}
void exemplul3(){
cout<<"Exemplul 3\n"<<endl;
int nrLin=3, nrCol=7;
//alocam static pointerul cap de tablou de pointeri cap de linie
int** tab;
//incarcam in tab adresa primului pointer cap de linie
tab=aloca3(nrLin, nrCol);
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
tab[i][j]=i+j;
}
}
for(int i=0;i<nrLin;i++){
for(int j=0;j<nrCol;j++){
cout<<tab[i][j]<<' ';
}
cout<<endl;
}

cout<<endl;
dealoca3(tab, nrLin);
}

int main(){
exemplul1();
exemplul2();
exemplul3();
return 0;
}
/*rezultat:
Exemplul 1
0 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
Exemplul 2
0 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
Exemplul 3
0 1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
Press any key to continue . . .
*/