السلام عليكم و رحمة الله و بركاته ...
لدي برنامج يعمل مصفوفة على حسب المعطيات التي تأتي من ملف معين ، و من ثم يتم أخذ جزء من هذه المصفوفة لحساب مجموع العناصر الموجودة في هذه المصفوفة الجزئية .
المشكلة هي بأني لما أقوم بتشغيل البرنامج لا تظهر لي أية أخطاء أو تحذيرات ، و المخرجات التي تظهر هي صحيحة (على الأقل على الـ sample input الذي لدي) ، و لكن عندما قمت بتسليم البرنامج إلى الدكتور قال لي أنه لديك runtime error - out of memory .
فما أطلبه منكم الآن هو التدقيق في الكود لإيجاد الخطأ.
// Problem : summon the matrices
#include <iostream>
#include <fstream>
using namespace std;
// a function that will find the maximium number
int max (int r_top, int r_bottom, int c_left, int c_right)
{
int a[] = {r_top, r_bottom, c_left, c_right};
int temp=0;
for (int i=0; i<4; i++)
{
if (a > a[temp])
temp= i;
}
return a[temp];
}
// a function that will check if the variables are in the valid range
bool check (int k, int r_top, int r_bottom, int c_left, int c_right)
{
return (k>0 && k<=1000 && r_top>=0 && r_bottom>=r_top && r_bottom<=100000 && c_left>=0 && c_right>=c_left && c_right<=100000) ;
}
// a function that will build the n by n array
void build (int** arr, int n, int k)
{
for (int i=0; i<n; i++)
{
int cnst= (k*i);
for (int j=0; j<n; j++)
{
arr[j] = cnst;
cnst+= k;
}
}
}
long sum (int** arr, int r_top, int r_bottom, int c_left, int c_right)
{
long sum = 0;
for (int i=r_top; i<=r_bottom; i++)
{
for (int j=c_left; j<=c_right; j++)
{
sum+= arr[j];
}
}
return sum;
}
int main()
{
ifstream in("matrix.in");
int n, k, r_top, r_bottom, c_left, c_right, end;
// reading data
in>>k>>r_top>>c_left>>r_bottom>>c_right;
// for the condition
end = k + r_top + r_bottom + c_left + c_right ;
while (!in.eof() && end!=-5)
{
if( check(k, r_top, r_bottom, c_left, c_right) )
{
// for the size of the big array
n = max(r_top, r_bottom, c_left, c_right) + 1 ;
// creating a dynamic 2d array
int ** arr;
arr = new int*[n];
for(int i = 0; i < n; i++)
arr = new int[n];
build(arr , n, k);
cout<<sum(arr, r_top, r_bottom, c_left, c_right)<<endl;
// deleting the array
for( int i = 0 ; i < n ; i++ )
delete [] arr ;
delete [] arr ;
}
in>>k>>r_top>>c_left>>r_bottom>>c_right;
end = k + r_top + r_bottom + c_left + c_right ;
}
}