Студопедия

КАТЕГОРИИ:


Архитектура-(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)

Automatic Allocation




Memory allocation

Pointers and arrays

In C++, arrays and pointers are essentially the same thing. Array name = pointer to first element (with index 0). By adding the statement

int hours[6];

we could then use the identifiers

hours[0] hours[1] hours[2] hours[3] hours[4] hours[5]

as though each referred to a separate variable. In fact, C++ implements arrays simply by regarding array identifiers such as "hours" as pointers. Thus if we add the integer pointer declaration

int *ptr;

to the same program, it is now perfectly legal to follow this by the assignment

ptr = hours;

After the execution of this statement, both "ptr" and "hours" point to the integer variable referred to as "hours[0]". Thus "hours[0]", "*hours", and "*ptr" are now all different names for the same variable. The variables "hours[1]", "hours[2]", etc. now also have alternative names. We can refer to them either as

*(hours + 1) *(hours + 2)...

or as

*(ptr + 1) *(ptr + 2)...

In this case, the "+ 2" is shorthand for "plus enough memory to store 2 integer values".

Difference between array and pointer:

– Declaring an array creates storage for the array

– Declaring a pointer creates no storage

Examples:

int a[10]; // creates storage for 10 ints, a is the address of the beginning of storage and address of

//the first array element

int * p = a; // p (and a) points to the first element (with index 0)

a[0]=7; // set the first element to 7

(*a == 7) // true (the same as (a[0]==7))

(*p == 7) // also true

*a = 9 // change the first element to 9

*p = -3; // change the first element to -3

*(a+1)=5; // set the second element to 5, the same as a[1]=5;

a[2] = 8; // change the third element to 8, the same is *(a+2)=8;

p[2] = 9; // change the third element to 9, the same is *(p+2)=9;

 

Each variable has some “storage” associated with it – memory space that contains the contents (value) of the variable. Size of this memory depends on type of variable:

ü pointers have 4 bytes

ü ints have 4 bytes

ü chars have 1 byte

Space is allocated at compile time automatically when variables are declared:

int a; // allocates 4 bytes for the scope of a

int b[10]; // allocates 40 contiguous bytes, for the scope of b

 

Space exists as long as the variable is in scope

ü space for variables in local scope goes away when the scope ends

ü variables are deallocated at the end of blocks {} and functions

ü global scope variables exist for the duration of the program

If an array is declared, enough space for the whole array is assigned, so:

int a[1000]

would use 2000 bytes (for 2 byte ints).

Wasteful if only a few of them are used in a particular run of the program. And problematic if more than 1000 elements are needed.

So there’s a case for being able to dynamically assign memory as a program runs, based on the particular needs for this run.




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


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


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



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




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