Here's a small piece of code I made for a dynamic array. I dont know if I am taking the best approach, but looks like its work in a rather simple way. Digs in a .txt file, and then input the values on screen. However when I quit the "While" loop, I cant find a way to display again values from that array.
Because youve declared the array in the loop, its life will end when the loop ends
If you declare it near string line(or somewhere else inside of main and outside of loops or if/else blocks), you can use array in the whole main function
Also;
1 2 3 4 5 6 7 8 9
while (! ratesfile.eof()) {
string *array = new string[max];
getline(ratesfile,line);
cout << line << endl;
array[i]=line;
i++;
max++;
}
What youre doing here is really, bad, and strange, wgeb you go through the loop, you allocate max strings to array, everytime after that, you allocate again, and again, overwriting what you already had, leaking memory, (and the previous string that array contained is also lost)
You should probably use a vector, or list of strings, or something else dynamic in size
(or make a really big array of strings if youre really lazy and just want it to work)
Thnks for your answer, well I guess I am going to switch to Vectors after all.
If I declare the array outside the loop, the max++, which is in the loop, will no more affect the array size, hence the array won't be dynamic anymore.
This is the only way I have found to make this array dynamic. Im gonna let this code be and start working on vectores, however for my understanding, is there a simple way here to declare the array outside the loop, and still make it dynamic ?
you allocate max strings to array, everytime after that, you allocate again, and again, overwriting what you already had, leaking memory, (and the previous string that array contained is also lost)
Seriously the code that i posted, will run, it wont work, the code that you posted, also wont work
Use some sort of dynamic array for this, list, vector, or just append to the string
(Or get the amount of lines, then allocate doing something like array = new string[lines])