New
Let’s imagine we need a new variable (e.g., x
) during the execution of the code and want to allocate the memory for x in a heap (dynamic memory). If we just create x
, our variable and static code memory will have no connections, and we can’t handle x
.
To have the opportunity to work with the variable, we should create the pointer in the stack (code memory) for our variable. In such a way, you will have access to x
for changing it:
In your code, use the operator new
to allocate the memory for the variable within the heap and the type of the desired variable (we have no names here). new
returns the address of the created variable:
new int;
We can also simultaneously declare the pointer x
, which is dereferenced to access the variable:
int *x = new int;
In the images, we gave the name to our dynamic variable to simplify the explanation. Actually, variables created in a heap have no name, only an address and a pointer to it.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Запитайте мені питання про цей предмет
Сумаризуйте цей розділ
Покажіть реальні приклади
Awesome!
Completion rate improved to 2.94
New
Свайпніть щоб показати меню
Let’s imagine we need a new variable (e.g., x
) during the execution of the code and want to allocate the memory for x in a heap (dynamic memory). If we just create x
, our variable and static code memory will have no connections, and we can’t handle x
.
To have the opportunity to work with the variable, we should create the pointer in the stack (code memory) for our variable. In such a way, you will have access to x
for changing it:
In your code, use the operator new
to allocate the memory for the variable within the heap and the type of the desired variable (we have no names here). new
returns the address of the created variable:
new int;
We can also simultaneously declare the pointer x
, which is dereferenced to access the variable:
int *x = new int;
In the images, we gave the name to our dynamic variable to simplify the explanation. Actually, variables created in a heap have no name, only an address and a pointer to it.
Дякуємо за ваш відгук!