Beginners question about array in C++
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Beginners question about array in C++

  1. #1
    Join Date
    Sep 2010
    Posts
    15

    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."

  2. #2
    Join Date
    Mar 2008
    Location
    Turin / Italy
    Posts
    178

    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?

  3. #3
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,313

    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 LITE 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.

  4. #4
    Join Date
    Sep 2010
    Posts
    15

    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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center