Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

8.15 Dynamic arrays Dynamic variables can also be arrays . Dynamic arrays are much more flexible than static arrays, because it is not necessary to

8.15 Dynamic arrays

Dynamic variables can also be arrays. Dynamic arrays are much more flexible than static arrays, because it is not necessary to know their size before running the program. The size of the array can be declared at runtime. Dynamic arrays use pointers to store their address, just like dynamic variables;

double *myarr; int size; cin >> size; myarr = new double[size]; 

You can then use myarr just as a regular array (you don't even need the * to access its content - more on this in class). Just remember to delete the array when you are no longer using it, especially since arrays are much better at taking up space in the heap than single variables.

delete [] myarr; 

Now, write a program that asks a user to specify how many numbers he wishes to write, then stores the values input by the user into a dynamic array.

How many numbers will you enter? 4 1 2 3 4 

Finally, it prints the array.

The array you entered is 1 2 3 4 

Remember to deallocate memory at the end of the program.

#include

using namespace std;

int main ()

{

int size,i;

int *p;

//Acquire array size from keyboard

//Create new dynamic array and store its address in p

if (p == NULL)

cout << "Error: memory could not be allocated";

else

{

//Fill array with user input

}

for (i=0; i

cout << p[i] << " ";

cout << endl;

//Delete array

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

b. Will there be one assigned leader?

Answered: 1 week ago

Question

d. How will lack of trust be handled?

Answered: 1 week ago

Question

b. Does senior management trust the team?

Answered: 1 week ago