Reputation: 2860
I currently have created a small program to learn about Lists. I allow the user to add random integers to the List. It adds them fine simply using DList.insert(number, position)
. Everything works fine for the first iteration, but when I allow the user to enter more random numbers, it gets rid of the previous numbers and then adds some more random numbers.
Since I'm new (rarely use it to program) to C++, I'm thinking that I'm making a very simple mistake. The issue seems to be that I'm just overwriting the old values in the List rather than adding new ones.
Here is what I'm doing,
List testList;
//Ask user for a number of elements to add
int num = get_number();
addRandInts(testList, num);
//I then give the user the option to add more or quit
Here is my addRandInts
:
void addRandInts(List dl, int num)
{
int random_max = 999;
int numIterations = dl.getSize() + num;
if(num > 0) {
cout << "Array Size: " << dl.getSize() << endl;
for(int i = dl.getSize(); i < numIterations; i++) {
dl.insert(rand() % random_max + 1, i);
}
} else {
cout << "You need to enter a positive integer" << endl;
}
dl.display(cout);
}
I can provide my List.insert(List, pos)
method if need be.
Here is the example output:
Please enter an integer number for the list: 5
Current Size: 0
42 486 341 527 189
//chance to add more to list
Please enter an integer number for the list: 3
Current Size: 0
740 490 388
So on the second run I was thinking that I should have the size of 5 and it should be adding 3 to it. Since I'm new to pointers and the like, should I be passing a pointer to the list rather than the list?
Upvotes: 0
Views: 435
Reputation: 73304
You're passing the list into the addRantInts() function by value, which means the function is modifying a copy of the list rather than the original. To avoid this, pass it by reference instead:
void addRandInts(List & dl, int num) // <-- note ampersand!
Upvotes: 3