-
February 11th, 2011, 03:09 AM
#1
Beginners question about array in C++
I am learning array in C++. This code compiles but when I run the program, it gives some error. Is there anything wrong in this code?
Code:
#include <iostream>
using namespace std;
int main()
{
int A[10][2];
for (int j=0; j<=10; j++)
{
for (int i=0; i<=2; i++)
{
A[j][i] = i+j;
printf("A[%d][%d] = %d,\t",j, i, A[j][i]);
}
printf("\n");
}
return 0;
}
When I run the exe file like this - Cpp1.exe > array.txt , nothing comes in to the array.txt and it says " Cpp1.exe has encountered a problem and needs to close. We are sorry for the inconvenience."
-
February 11th, 2011, 03:31 AM
#2
Re: Beginners question about array in C++
Code:
for (int j=0; j<=10; j++)
...........
for (int i=0; i<=2; i++)
check the bounds for i and j. Do you see there's something wrong with them?
-
February 11th, 2011, 03:58 AM
#3
Re: Beginners question about array in C++
Arrays start at 0 in C++, so the last index is always 1 less than the capacity.
An easy way to loop without thinking to much is to never include the last index in your range, by using strict weak ordering:
Code:
for (int i=0; i<Size; ++i) //Good Form
The alternative is to use -1, but this is rarelly done.
Code:
for (int i=0; i<=Size-1; ++i) //Meh
As for your form:
Code:
for (int i=0; i<=Size; ++i) //BAD!!!
This is just plain wrong, as you will reference array[Size], which is out of bounds.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
-
February 11th, 2011, 05:51 AM
#4
Re: Beginners question about array in C++
Thank you very much for the replies.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|