tags:

views:

2088

answers:

11

suppose I declare a dynamic array like

int *dynArray = new int [1];

which is initialized with an unknown amount of int values at some point.

How would I iterate till the end of my array of unknown size?

Also, if it read a blank space would its corresponding position in the array end up junked?

Copying Input From users post below:

Thing is:

a) I'm not allowed to use STL (means: no )

b) I want to decompose a string into its characters and store them. So far I wanted to use a function like this:

 string breakLine (string line){


         int lineSize = line.size();

         const char *aux;

         aux=line.data();

         int index=0;


         while (index<=lineSize){
         mySynonyms[index]=aux[index]; 

         index++;
         }

I thought that the array aux would end up junked if there was a large blank space between the two numbers to be stored (apparently not). And I was wondering if there was a way to iterate till an undefined end in this type of array. Thanks for you answers.

+4  A: 

No portable way of doing this. Either pass the size together with the array, or, better, use a standard container such as std::vector

Nemanja Trifunovic
+15  A: 

You don't: wrap the array into a structure that remembers its length: std::vector.

std::vector v(1);
std::for_each( v.begin(), v.end(), ... );
xtofl
+1  A: 

Your code needs to keep to track of the array, so the size would never be unknown. (Or you would have to use some library with code that does this.)

I don't understand the last part of your quesiton. Could you elaborate?

Guge
+2  A: 

Short answer is that you can't. If you have a pointer to the first element of an array, you can't know what the size of the array is. Why do you want to use a array in the first place. You would be much better off using a std::vector if your array can change size dynamically, or a boost::Array if it will be a fixed size.

I don't understand your second question.

KeithB
A: 

Use a vector, which has a vector.size() function that returns an integer and a vector.end() function that returns an iterator.

Logan Serman
A: 

You could create a simple Vector class that has only the methods you need. I actually had to recreate the Vector class for a class that I took this year, it's not very difficult.

Logan Serman
Bad idea. use std::vector, it is known to be correct. It harder than you think to get correct and exception safe.
Martin York
+1  A: 

You explained in your post below that you want to look at the guts of a std::string.

If you are expecting your stirng to be like a c-string (aka doesn't contain NULLs), then use line.c_str() instead of line.data(). This will guarantee that aux points to a null terminates c-style string.

After that you can iterate until aux[index] == '\0';

Otherwise, you can use line.data() and string.length/size to get it's size like in your example.

However, "decomposing a string into its characters" is pretty pointless, a string is an array of characters. Just make of copy of the string and store that. You are allowed to do:

char ch = line[index];

Better yet, use iterators on the original string!

for(std::string::const_iterator it = line.begin(); it != line.end(); ++it) {
    const char ch = *it;
    // do whatever with ch
}
Evan Teran
Except that std::strings can legally contain '\0' characters. Just use iterators or call string::length() and iterate by index.
Eclipse
Indeed, I'll reword my answer
Evan Teran
A: 

If there's a value that cannot be valid, you can use that as a sentinel, and make sure all of your arrays are terminated with that. Of course, it's error-prone and will cause hard-to-find bugs when you happen to miss doing it once, but that's what we used to do while reading files in FORTRAN (back in the all-caps days, and before END= became standard).

Yes, I'm dating myself.

David Thornley
+1  A: 

a) I'm not allowed to use STL (means: no )

What?? Who's moronic idea was that?

std::vector isn't part of the "STL" (which is a copyrighted product of HP), but is (and has been for nearly a decade) part of the C++ Language Standard.

James Curran
+1  A: 

If you're not allowed to use the STL (for whatever reason), the first thing you want to do is actually to implement your own version of it – at least the parts you need, with the level of customizability you need. For example, it's probably overkill to make your own vector class parametrizable with a custom allocator. But nevertheless do implement your own lightweight vector. Everything else will result in a bad, hardly maintainable solution.

Konrad Rudolph
A: 

This smells like homework, and the teacher's objective is to give you a feeling of what it takes to implement dynamic arrays. So far you're getting an F.

You need to realize that when you allocate memory like this

int *dynArray = new int [1];

you allocate precisely one integer, not an indefinite number of integers to be expanded by some unidentified magic. Most importantly, you can only say

dynArray[0] = 78;

but you cannot say

dynArray[1] = 8973;

The element at index 1 does not exist, you're stepping into memory that was not reserved for you. This particular violation will result in a crash later on, when you deallocate the array, because the memory where you stored 8973 belongs to the heap management data structures, and you corrupted your heap.

As many other responders mention, you must know how many elements you have in the array at all times. So, you have to do something along the lines of

int arraySize = 1;
int *dynArray = new int [arraySize];

arraySize goes together with the array, and is best combined with dynArray in one C++ object.

Now, before you assign to dynarray[1], you have to re-allocate the array:

if (index > arraySize) {
  int newSize = index+1;
  int *newArray = new int[newSize]
  // don't forget to copy the data from old array to new
  memcpy(newarray dynArray, sizeof *newArray * arraySize);
  arraySize = newSize;
  dynArray = newArray;      
}
// now you're ready!
dynArray[index] = value;

Now, if you want to make it a bit more efficient, you allocate more than you need, so you don't have to allocate each time you add an element. I'll leave this as an exercise to the reader.

And after doing all this, you get to submit your homework and you get to appreciate the humble std::vector that does all of this for you, plus a lot more.

Arkadiy