КАТЕГОРИИ: Архитектура-(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 Arrays
Dynamic Memory In addition to the program stack (which is used for storing global variables and stack frames for function calls), another memory area, called the heap, is provided. The heap is used for dynamically allocating memory blocks during program execution. As a result, it is also called dynamic memory. Similarly, the program stack is also called static memory. The new operator can be used to allocate memory at execution (run) time. It takes the following general form: pointer_variable = new data_type; Here, pointer_variable is a pointer of type data_type. The new operator allocates sufficient memory to hold a data object of type data_type and returns the address of this memory.
int *ptr1 = new int; float *ptr2 = new float; Primitive types allocated from the heap via new can be initialized with some user-specified value by enclosing the value within parentheses immediately after the type name. For example, int *ptr = new int (65); //allocates 4 bytes in dynamic memory and place in there number 65
Memory allocated from the heap does not obey the same scope rules as normal variables. For example, void F () { int* a = new int; //... } when F returns, the local variable a is destroyed, but the memory block pointed to by a is not. The latter remains allocated until explicitly released by the programmer. The delete operator is used for releasing memory blocks allocated by new. It takes a pointer as argument and releases the memory block to which it points. For example: delete a; Often, we do not know the size of an array at compile time. If we try to write: int N; N=SrtToInt(Edit1->Text); int a [N]; – compiler rejects this, because N is a variable. In this case we must use dynamic array. Dynamic array is array, which: ü allocates in heap (dynamic memory) with new operator; ü may have a variable size (but its value must be obtained before array declaration). To get memory for an array of some primitive type using new, write the keyword new followed by the number of array elements enclosed within square brackets. int *a = new int [ 5 ]; After this declaration we can operate with dynamic array as with static one. For example, to input the values of array a from Memo1, we can write: for (int i = 0; i < 5; i++) a [ i ] = StrToInt(Memo1->Lines->Strings[i]);
Note that it is not possible to initialize the individual elements of an array created when using new. To destroy the dynamic array, we write delete [] a; The "[]" brackets are important. They signal the program to destroy all 5 variables, not just the first. Dynamic arrays can be passed as function parameters just like ordinary arrays.
Дата добавления: 2014-01-11; Просмотров: 474; Нарушение авторских прав?; Мы поможем в написании вашей работы! Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет |