Question
Dynamic memory allocation: C++ let's you request memory from the OS using the new operator, and use it like individual variables or arrays. Using it
Dynamic memory allocation:
C++ let's you request memory from the OS using the new operator, and use it like individual variables or arrays. Using it for single variables is more important for object-oriented programming and data structures (courses such as CS 1412 and CS 2413), but we'll do it here with ints and floats. Using it for dynamically allocated arrays is VERY useful, however, so be sure you understand this part of the lab when you're done!
Here is a sample program which allocates a double and uses it, then allocates a block of 10 doubles and uses them as an array. It also demonstrates how to pass pointers by value and by reference to functions. Compile and run it, discuss it with your partner, and make sure you understand how it works.
#include#include #include using namespace std; void print_array(double * p, int npts); // function with pass-by-value pointer parameter void change_ptr (double * &p, int n); // function with pass-by-reference pointer parameter int main( ) { double *q = NULL, *r = NULL; // you should always initialize pointers to NULL cout << fixed << setprecision(4); // allocate a double. q = new double; *q = acos(-1.0); cout << "pi is "<< *q << endl; delete q; // We're done with it. give it back. q = NULL; // point it back to NULL to flag that it's not pointing at valid memory. // allocate a block of 10 doubles and put some values in them. q = new double[10]; for (int i=0;i<10;i++) q[i] = 1.0/(i+1); cout << "q contains: "<
Write a program which:
dynamically allocates an array of 5 integers
uses a loop to set the elements to 5, 10, 15, 20 and 25
uses a second loop to output the elements of the array.
be sure you use a second loop for this!
deletes the array.
Compare programs with your partners, make sure youre all getting it, and add the following:
Move the array-printing to a function print_array
Write a function create_array with the following prototype: void create_array(int * &p, int size, int initval);
this function should dynamically allocate an array and set all elements to initval. Note: you'll need to use a loop to set all the values.
use both these functions in your program. Have your program create a dynamically allocated array of 10 elements and initialize it to all zeros (and print it out), then have it create another dynamically allocated array of 20 elements, and initialize it to all 999's (and then print it).
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started