Well, first of all you're creating a memory leak on line 9 of your main file. You are allocating memory with
list1.list
, but
list1.list
already points to memory you allocated in the ArrayList constructor, so you're losing the pointer. It also appears that your size member is going to be incorrect because when you reallocate memory with
list1.list
, you're setting the size to 6, but the class expects it to be 5. This is an excellent example of why encapsulation is important, and should be used. Problems like this can be avoided by making data members like
list
, private, which I recommend you do.
As for your problem involving the strange output, it's because whenever an negative number in the list of whatever object is calling
CopyPositiveValues
is found, it skips it and increments i. This means that
obj1.list[i]
is going to be left uninitialized, hence the junk value that you end up with. To fix this, just have a separate variable for whatever the next uninitialized element in
obj1.list
is, and only increment it when you add a value to the list, like this:
1 2 3 4 5 6 7
|
int obj1_index = 0;
for(int i = 0; i <= size; ++i) {
if(list[i]>=0) {
obj1.list[obj1_index] = list[i];
++obj1_index;
}
}
|