1/15
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
How do you allocate memory on the heap in C++?
Memory is allocated on the heap using the new keyword. For example: new int; allocates memory for a single integer on the heap (with nothing assigned to it).
NOTE: This code doesn’t make sense on it’s own. It must have a pointer like: int* ptr = new int(10);
How do you declare an integer pointer in C++?
To declare an integer pointer: int * p_i; creates a pointer to an integer (but with nothing actually assigned).
How do you assign a pointer to newly allocated memory?
You assign a pointer to newly allocated memory like this: p_i = new int; assigns memory for an integer to the pointer p_i.
To put simply, this assigns memory for a new integer variable and then sets the pointer to that location. Full code:
How do you take the address of a non-pointer variable?
You take the address of a non-pointer variable using the unary & operator. For example, int * p_i = &i; takes the address of i and assigns it to p_i.
Reminder: int * p_i is creating a new pointer, not dereferencing it.
How do you free a block of memory allocated with new?
You free a block of memory using the delete operator. For example: delete p_array; frees the memory pointed to by p_array (notice it is a pointer to a variable).