C++ Primer Plus 5th Ed. Help

Having trouble with Problem 1 on Chapter 5. How would I make a dynamic array that reads the integers in between two that the user types. For example: The user types in 1 and 10. I want the array to hold all int between 1 and 10.

{1, 2, 3, 4, 5,6 ,7, 8, 9, 10}.

I've been scouring the book, but cannot figure it out on my own.
Last edited on
Would this site's page on dynamic allocation help?
http://cplusplus.com/doc/tutorial/dynamic/

After that, all you need is a for-loop with well-set boundaries to fill your array.

EDIT: Late. I suppose you could also use an std::vector as ciphermagi is proposing, though I think the point of the exercise was to learn how to use new[].

-Albatross
Last edited on
I just figured that a vector would be more memory safe for a new user.
std::vector is a much better idea for the sake of learning - Primer Plus is one of many beginner books which hasn't really been restructured since its early editions sometime in the 1990's - so it ends up teaching things in the wrong order (I think vectors are tucked away at the back somewhere rather than near the beginning where they should be).
If you were not a beginner I would advice you to write the following. Let a and b are two integer values, then the code will look like

1
2
3
std::vector v( b - a + 1 );

std::iota( v.begin(), v.end(), a );


Instead of this code maybe you should dynamically allocate memory for an array, and then in loop fill its elements with values.

1
2
3
int *v = new int[b - a + 1];

for ( int i = 0; i < b - a + 1; i++ ) v[i] = a + i;
Last edited on
Okay I got it. Thank you all for your help.
Topic archived. No new replies allowed.