Sign in to follow this  
BlueBan007

2D arrays question ??

Recommended Posts

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[i][j]=puts;
			cout<<array1[i][j]<<"\t";
			puts++;

		}
		cout<<endl;
		}

system("pause");
return 0;
}

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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++) {





Share this post


Link to post
Share on other sites
@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.

Share this post


Link to post
Share on other sites
Try it. Look at the output:

#include <iostream>
int main(int, char **) {
for(int j=0;j<4;j++) std::cout << j << std::endl;
}


Share this post


Link to post
Share on other sites
Your for loop breaks down like so:

int j=0;
beginning:
if !(j < 4) goto end;
{
// for loop body
}
j++
goto beginning;
end:

So the first time through the loop j is 0, which is less than 4, so it goes through the body and gets incremented to 1. 1 is less than 4, so it goes through the body and gets incremented to 2. 2 is less than 4, so it goes through the body and gets incremented to 3. 3 is less than 4, so it goes through the body and gets incremented to 4. 4 is not less than 4, so it skips the body and goes to the end.

Share this post


Link to post
Share on other sites
That's why we normally write the loop with strict inequality (< rather than <=): because then the limit is the same number as the size of the array. Using a number directly is easier to remember than having to subtract one from it.

Arrays are zero-based in C++. This is a good thing. Learn to work with it. In the long run, it makes your life easier. (There are languages out there that use 1-based arrays by default, but they're definitely in the minority.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this