Question

I am new to C++. I am working on a problem from class. We must use Dynamic Arrays to read words from a file.

Here are my simple questions.

  1. Does Dynamic Array imply the use of a pointer? Meaning we point at our new array made.
  2. In Java, ArrayList can be created and size changes dynamically. But to me in C++, does using a dynamic array mean to set the size of the array to a large number and then dynamically allocate that array?
  3. Is there no way to chop off the excess indexes from the dynamic array? So then delete the array at the end is the only choice I have in C++?

Thanks, pointers and dynamic arrays can only be used. Thank you.

Was it helpful?

Solution

Java ArrayList is only comparable to C++ Vector. A normal dynamic array does not change it's size at runtime so if you declare a dynamic int array in c++:

int *arr = new int[10];

The size of that array will remain at 10.

However if you use vector:

std::vector<int> arr(10);

Then when this vector is filled past 10 elements, the vector object automatically allocates more memory for itself.

So to answer your question, dynamic array implies making use of a pointer to keep track of the memory location where the heap-allocated array has been placed. But if you use vector, this is handled for you internally

OTHER TIPS

I suppose dynamic array could refer either. Look at what you have to do and decide. Does it make scene to use an array where the size is fixed? I'm guessing that a vector would be the best here since you probably don't know ahead of time how large the file is.

std::vector<string> words;

Also just for your information the vector class simply stores a pointer to a dynamically allocated array. It creates a new one whenever you need more room, copies over the the data from the old array, and the deletes it. This all happens behind the scenes.

The C++ equivalent of a Java ArrayList is std::vector. You use the capitalized term "Dynamic Array" as if it has a specific meaning rather than the generic adjective "dynamic" applied to the concept "array". A "dynamic array" in C++ spec lingo is a local variable that has a fixed size, set when it is initialized/created, but that may get a different size each time the scope is entered (and the array recreated). Since it's local to a scope, its not too useful for storing stuff read from a file other than temporarily. C++ also has heap-allocated arrays which have their size set when created (as with a dynamic array), but which persist until explicitly deleted, which might be more useful. These are "dynamic" in the general adjective sense, but are not "dynamic arrays" in the spec sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top