2D arrays question ??

Started by
10 comments, last by Zahlman 14 years, 11 months ago
sorry if this is a stupid question, but I'm testing out some arrays stuff, and I received this error: Run-Time Check Failure #2 - Stack around the variable 'array1' was corrupted. this is the code:


#include <iostream>

using namespace std;

int main(int argc, char *argv[]){

	int array1[5][5];
	int puts=1;

		for(int i=1;i<=5;i++){
		for(int j=1;j<=5;j++){
			
			array1[j]=puts;
			cout<<array1[j]<<"\t";
			puts++;

		}
		cout<<endl;
		}

system("pause");
return 0;
}

Advertisement
Arrays in programming are (almost?) always 0 based. That is, the first item is at [0] not at [1]

for(int i=1;i<=5;i++) {for(int j=1;j<=5;j++) {


should be

for(int i=0;i<5;i++) {for(int j=0;j<5;j++) {


-me
Array indices go from 0 to size - 1; not 1 to size.
wow im foolish lol, thanks
Quote:Original post by Palidine
for(int i=0;i<5;i++) {
for(int j=0;j<5;j++) {


You just made it have six terms. It should only be five.
the way it should be put:
for(int i=0;i<4;i++) {for(int j=0;j<4;j++) {




@X19OV1: Palidine's code is fine, it runs from 0 to 4 (not 5, because 5 is not lower than 5, so the loop will bail out there). Your code only runs up to 3.
Create-ivity - a game development blog Mouseover for more information.
Quote:Original post by Captain P
Your code only runs up to 3.


How does my code only run up to 3?

Try it. Look at the output:
#include <iostream>int main(int, char **) {  for(int j=0;j<4;j++) std::cout << j << std::endl;}


Hmmm, I thought it was counted:
0, 1, 2, 3, 4
I see now. It's written as: <4.^^
Because j < 4, the only way that is possible it at 3 or less. So it can never reach 4.

theTroll

This topic is closed to new replies.

Advertisement