Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Dynamic Matrixes




We can create 2-d arrays of variable size based on pointers, using dynamic data. To create n x m array x:

int** x;

x = new int* [n];

for(i = 0; i<n; i++)

x[i] = new int[m];

This code allocates memory for n pointers to pointers to integers (pointers to matrix rows – vertical one-dimensional array x on the figure below). Variable x now points to start of this block (array) of pointers (x[0] is a pointer to the first matrix row, x[1] is a pointer to the second matrix row, etc.). For each of these pointers, allocates memory for m integers (for each row separately) and assign the address of the beginning of this memory to x[i]. The array elements x[i] now point to matrix rows. We can write x[i][j] to access an element in row i and column j.

  x            
           
               
             
               
             

 

To free memory, allocated this way for dynamic matrix, we must at first free memory allocated for each row separately and then free memory allocated for array of pointers to rows:

for(int i=0;i<n;i++) delete[] x[i]; delete[] x;

Example 1 of program with dynamic matrix:

Enter float matrix n x m and calculate the product of positive elements.

 

double p=1;

float **a = new float* [n]; //Allocate memory for array a of pointers to matrix rows

for (int i=0; i<n;i++)

a[i]=new float[m]; //Allocate memory for each row (it contains m elements) separately

for (int i=0; i<n;i++)

for (int j=0; j<m;j++)

{a[i][j]=StrToFloat(StringGrid1->Cells[j][i]);

if(a[i][j]>0)

p*=a[i][j];

}

Edit3->Text=FloatToStr(p);

for (int i=0; i<n;i++)

delete []a[i]; //Free memory allocated for matrix rows

delete []a; //Free memory allocated for array a

}

There is one more approach to work with dynamic matrixes. You remember, that matrix elements are stored in memory in one line. We can allocate memory for the matrix in standard way. It will be the same as one-dimensional array of n*m elements:

float *a=new float [n*m];

If n and m are constants, we can write two dimensions separately. For example, float matrix 3x5:

float *a=new float [3][5];

                             
                             
0-th row 1-st row 2-nd row

To access matrix elements we have to calculate its index: a[i*m+j] (we cannot use two indexes separately as in static matrix). For example, highlighted element (in figure above) is a[1*5+3]=a[8].

To free memory, allocated in this way, we must write:

delete []a;

Example 1 of program with dynamic matrix (II approach of memory allocation):

Enter float matrix n x m and calculate the product of positive elements.

double p=1;

float *a = new [n*m]; //Allocate memory for all matrix elements, placed in one line

for (int i=0; i<n;i++)

for (int j=0; j<m;j++)

{a[i*m+j]=StrToFloat(StringGrid1->Cells[j][i]);

if(a[i*m+j]>0)

p*=a[i*m+j]; }

 

Edit3->Text=FloatToStr(p);

delete [] a;

We can access matrix elements with pointers: a[i*m+j]. The same program with pointers:

 

double p=1;

float *a = new [n*m]; //Allocate memory for all matrix elements, placed in one line

for (int i=0; i<n;i++)

for (int j=0; j<m;j++)

{*(a+i*m+j)=StrToFloat(StringGrid1->Cells[j][i]);

if(*(a+i*m+j)>0)

p*=*(a+i*m+j); }

 

Edit3->Text=FloatToStr(p);

delete [] a;

 

The pointer has following advantages:

ü It allows to pass variables, arrays, functions, strings and structures as function arguments.

ü A pointer allows to return structured variable from a function.

ü It provides function which modify their calling arguments.

ü It supports dynamic allocation and deallocation of memory segments.

ü With the help of pointer, variable can be swapped without physically moving them.




Поделиться с друзьями:


Дата добавления: 2014-01-11; Просмотров: 466; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.009 сек.