Create a directory ex3 and store in this directory all the files corresponding to this exercise.
Create a file: "test_pointers.cpp" then write and complete the following code by writing the code corresponding to the explanations in comments:
// test_pointers.cpp
#include <iostream>
int main()
{
//
// 1. declare a variable p as a pointer to an int
// 2. allocate memory on the heap corresponding to one int and make p points to this location
// 3. store the value "1" at the memory location pointed to by p
std::cout << "Value at the memory pointed to by p: "
<< *p << std::endl;
// 4. delete the memory pointed to by p
//
int a[5] = {1, 2, 3, 4, 5};
// 5. make p points to the beginning of the array a
// 6. print the content of p and the content of a[0]
// 7. increase p to make it point to the next element of a
std::cout << "Value at the memory pointed to by p: "
<< *p << std::endl;
// 8. make p points to the fourth element of the array
// by assigning the address of this element to p
p = &a[0];
while (p != &a[5]) {
// 9. print the value pointed to by p
// 10. increase p to make it points to the next element of a
}
//
int n = 10;
// 11. Declare a variable "d_array" as a pointer to double and
// make it point to an array of "n" element of type "double" created on the heap
// 12. Store in each d_array[i] (for i=0 to n-1) the value (double)i / 2.0;
for (int i = 0; i < n; i++)
{
std::cout << d_array[i] << std::endl;
}
// 13. delete the previously allocated memory
//
int m = 5;
int** i_array;
// 14. allocate memory for a 2d array of size m * n on the heap.
// Make i_array points to this 2d array.
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
i_array[i][j] = i + j;
// 15. display the content of var: i_array[i][j] (0 <= i <= m-1, 0 <= j <= n-1)
// 16. delete the memory allocated for the 2d array
}
Step 1: Create the files: "swap.h", "swap.cpp" and "test_swap.cpp". In "swap.h" write the prototype (i.e. the function declaration) for the function "swap()" that takes two arguments of type 'int' and swap their contents. In "swap.cpp" write the implementation of the function "swap()". In "test_swap.cpp" type and complete the following code:
// test_swap.cpp
// <- Include all the necessary headers here
int main() {
int i = 1;
int j = 2;
swap(i, j);
std::cout << "i=" << i << " and j=" << j << std::endl;
}
Step 2: Create the files: "swap_ptr.h", "swap_ptr.cpp" and "test_swap_ptr.cpp". In "swap_ptr.h" write the prototype for a function "swap_ptr()" that takes two pointers to 'int' and swap the content of the memory pointed by these pointers. In "swap_ptr.cpp" write the implementation of the function "swap_ptr()" declared in the header "swap_ptr.h". In "test_swap_ptr.cpp" type and complete the following code:
// test_swap_ptr.cpp"
// <- Include all the necessary headers here
int main() {
int i = 1;
int j = 2;
/* call swap_ptr() here in order to swap the contents of i and j */
std::cout << "i=" << i << " and j=" << j << std::endl;
}