Friday, July 31, 2009

Increasing array size?

I have an assignment to write a program that ask users to input id numbers and donations. then i am supposed to ask the user to enter an id number to search the list to see if the ID number matches any in the list. If the ID number does not match any in the list, it is supposed to ask for a new donation amount, and output the new list of all the ids an donations. Mu problem is i orignally declared the ID and donation arrays of 5 each. so now when I call the function to add a new donation and id to the list, i am increasing the variable with plus one, but i output it, i am getting negative numbers which makes me think the array is out of bounds.


This is the function. the "int c" is the variable holding the array size.





void addADonor(int idNumbers[], int donations[], int%26amp; c)


{





int g, v;


c++;





cout%26lt;%26lt;"\n\nRe-enter the new ID and donation: ";





for (g=c, v = c; g %26lt; c + 1 , v %26lt; c + 1 ; g++, v++)


cin%26gt;%26gt;idNumbers[g]%26gt;%26gt;donations[v];


}

Increasing array size?
Incrementing a variable that was used to initially set the size of an array doesn't magically increase the size of the array. In order to make an array larger, you need to create a new and bigger array, copy over all the values from the existing array, and then destroy the old array.





If this project is suppose to make you learn how to do this type of thing, then you'll have to make a function that does this. If that's not the purpose of the project, you might consider just making the arrays really large. It's bad style, but it works.





Incidentally, you don't need two loop counters. Since they both always have the same value, you can use just one counter.
Reply:Do you *need* to use arrays? Is that part of the assignment? If so then Nisovin gave a good answer.





The obvious lesson here is that an array is the wrong data structure to use if you don't know in advance how many items you are expected to handle.





You can use a vector (assuming this is C++) but that basically just does (under the covers) what Nisovin was describing.





What you really want is a linked list.


No comments:

Post a Comment