146k views
3 votes
Given the variable ip, already declared as a pointer to an integer, write the code to dynamically allocate memory for a single integer value, assign the resulting pointer to ip, and initialize the integer value to 27.

1 Answer

2 votes

Answer:

In C++:

int *ip;

ip = new int;

*ip = 27;

Step-by-step explanation:

First of all, let us have a look at the methods of memory allocation to a variable.

1. Compile Time: The memory gets allocated to the variable at the time of compilation of code only. It is also called static allocation of memory.

Code example:

int a = 5;

2. Run Time: The memory is allocated to the variable on the fly i.e. during the execution of the program. It is also called dynamic allocation of memory.

Now, we have to write code for a variable ip, which is an integer pointer to dynamically allocate memory for a single integer value and then initialize the integer value 27 to it.

Initializing a variable means assigning a value to variable for the first time.

Writing the code in C++ programming language:

int *ip; // Declaring the variable ip as a pointer to an integer

ip = new int; // Dynamically allocating memory for a single integer value

*ip = 27; // Initializing the integer value to 27.

User N Dorigatti
by
3.2k points