Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when running code

Tags:

c++

text-files

I have tried the following code but I get an error when running it. I have used Debugger but I can't understand the errors in the call stack.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int a[10][2],i,j, b[10],max, min;
    ifstream f("numere.txt");

    for(i=1;i<=10;i++)
    {
        for(j=1;j<=2;j++)
        {
            f>>a[i][j];
            b[i]=0;
        }
    }

    for(i=1;i<=10;i++)
    {
        for(j=1;j<=2;j++)
        {
            b[i]=b[i]+a[i][j];
        }
    }

    max=b[1];
    min=b[1];

    for(i=1;i<=5;i++)
    {
        if(max<=b[i]) max=b[i];
        if(min>=b[i]) min=b[i];
    }

    cout<<"Cea mai mare suma este:"<< max<<endl;
    cout<<"Cea mai mica suma este:"<< min<<endl;


    f.close();
    return 0;

}

Call Stack Screenshot

Please, help me. I am a beginner and I have never worked with files before.


1 Answers

You have at least one error: array index out of bounds:

 for(i= 0;i<10;i++)
{   //^^^
    for(j=0;j< 2;j++)
    { //^^^
        f>>a[i][j];
        b[i]=0; //Why you put b[i] here??
    }
}

Since you declare a[10][2] and array indices start from 0, not 1 in C++. You will access memory that does not belong to a (and b).

like image 142
taocp Avatar answered Jun 03 '26 06:06

taocp