-
Confused.. Help please?
Since I learned arrays a couple of days ago I got really annoyed when this program didn't worked, could anyone give me a hint?
Code:
#include <iostream.h>
#include <cstdio> //required to pause
using namespace std; //required to pause
int main()
{
int array[4] = { 10, 20, 30, 40 };
cout<<array[1]<<endl;
cout<<array[2]<<endl;
cout<<array[3]<<endl;
cout<<array[4]<<endl;
getchar(); //pause
getchar(); //pause
return 0;
}
What happened is, instead of outputting
it outputted
-
> int array[4] = { 10, 20, 30, 40 };
This declares an array from 0 to 3. There is no index 4.
So: Code:
cout<<array[0]<<endl;
cout<<array[1]<<endl;
cout<<array[2]<<endl;
cout<<array[3]<<endl;
-
-
And if you've learned for-loops, you can print the array like this:
Code:
for (int i=0; i<4; i++)
cout<<array[i]<<endl;
-
classic example of accessing an array outside it's boundry. :rolleyes: