Dynamic memory allocation: C++ let\'s you request memory from the OS using the n
ID: 3820717 • Letter: D
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 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.
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 you’re 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).
Explanation / Answer
separated two programs by =======
#include <iostream>
using namespace std;
void print_array(int * p, int npts);
int main( )
{
int *arr;
arr = new int[5];
for(int i = 0; i < 5; i++)
{
arr[i] = (i+1)*5;
}
print_array(arr, 5);
delete [] arr;
}
void print_array(int * p, int npts)
{
for (int i=0; i<npts; i++)
cout << *p++ << ' ';
cout << endl;
}
=========================================================================
#include <iostream>
using namespace std;
void create_array(int * &p, int size, int initval);
void print_array(int * p, int npts);
int main( )
{
int *arr = NULL, *arr2;
create_array(arr, 10, 0);
print_array(arr, 10);
create_array(arr2, 20, 999);
print_array(arr2, 20);
delete [] arr2;
delete [] arr;
}
void print_array(int * p, int npts)
{
for (int i=0; i<npts; i++)
cout << *p++ << ' ';
cout << endl;
}
void create_array(int * &p, int size, int initval)
{
p = new int[size];
for(int i = 0; i < size; i++)
{
p[i] = initval;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.