Another easy4u loop question
Well, I've finally figured a few things out on my own before coming to you guys, but here I am again!
This code down here seems as straight-forward as I can think of, so why does it crash? I've tried everything. I don't think the loop ever stops.
I'm just attempting to take information out of one array and putting it into another. My counters work ok ( I think). Can you believe that I've been working on making this for about a week! Today I finally got it *yippie* then it crashes lol.
I've included only the part that crashes, the rest works fine:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int MAX=12;
const int iMAX=31;
long months[iMAX] = { 31,29,31,30,31,30,31,31,30,31,30,31 };
int hold[MAX];
int i=0;
hold[i] = months[i];
while(i < MAX)
{
cout << i+1 << ": " << months[i]
<< " "
<< "Hold= " << hold[i] << "\n";
i++;
hold[i] = months[i];
}
cout << "\n\nNotice how this program crashes! Why?\n\n";
system("pause");
return 0;
}
-----
Also, now learning pointers, they are awful dreaded gross things, my book seems to jump from simple to "masterful" in about 2 pages, can anyone recommend a good book?
Thanks again people,
Rob Sitter
Last post to close this thread>> Told you it was easy4u lol :)
Quote:
Originally Posted by Daved
Notice that you increment i near the end of the loop, but then copy the elements from months to hold after the increment. The last time through the loop, i will be one less than MAX, then you increment it to be MAX, and then you attempt to assign the element at index MAX in months to the space at index MAX in hold. Array indexes are 0 based, so you are accessing the array passed its bounds leading to a crash.
You should do the increment after you make the assignment .
Ok, thanks!
Rob Sitter