3 pts Understand PointersDynamic Memory Write a function 3 d

(3 pts) Understand Pointers/Dynamic Memory Write a function 3 different ways in C++ to create memory on the heap and assign it to a pointer outside the function. Remember, you can return an address or change what a pointer points to in a function by passing the pointer by reference or by passing the address of the pointer. What if you want to change the contents of what the pointer points to? Make a function that will set the contents of the space on the heap. Do you still need to pass by reference or the address of the pointer? Why or why not? How will you delete the memory off the heap? Try doing it outside a function, now inside a function. You can check to see if you have any memory leaks using valgrind. %valgrind program_exe

Solution

Three ways of passing arguements to c++ function is:
(i) pass by value
(ii) pass by reference
(iii) passing address of the pointer.

PASS BY VALUE:
-----------------------
fun(int a, int b){
  
}
..
int a = 3,b=4;
fun(a,b)

Here changing values in function wont alter original values.

-------------------------------------------------------------------------------------------
PASS BY REFERENCE
-------------------
void fun(int *ptr){
  
}
.. fun(&val);

Here changing values in function will alter original values.

--------------------------------------------------------------------------
PASS BY ADDRESS:
------------------
void fun(int *ptr){
  
}

.. fun(val);

Here changing values in function wont alter original values although we are passing address of pointer.

---------------------------------------------------------------------------------------------------------------
For the heap function we can do either passing arguements by reference or address.
----------------------------------------------------------------------------------------------------------
Pass by reference is not recomended since if changes done unexpectedly will alter original values and might overwrite the results.
So passs by address is suggestible or simply pass by value is better choice.

(3 pts) Understand Pointers/Dynamic Memory Write a function 3 different ways in C++ to create memory on the heap and assign it to a pointer outside the function

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site