Recently I have been solving some hackerranks tasks.In advance I want to tell that I know basics of c++ (I read and made tasks from book "Programming: Principles and Practice Using C++") .. Unfortunately in one of these problem I got stuck and from few hours i can't move forward. When I tried to fix it, I experienced a bunch of runtime or segmentation errors. I know that errors are produced by my int** arr
when program tries to modify it , but I can't figure out by what are caused. Also I aware that program can have more bugs which now i can't spot due to this first bad part of program. I know that further i program are more mistakes but now I focus on the first issue. I could write this program by using list or array but i want to challenge myself and do it with more low programing tools.
There is link to problem and below is my whole code
#include <vector>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <limits>
#include <cstring>
#include <string>
#include <cassert>
using namespace std;
int N ,q;
int main()
{
int lastAnswer=0;
cin>>N>>q;
int** arr = new int*[N];
for(int i=0;i<N;i++)
{
arr[i]=nullptr;
}
for(int i=0; i<q;i++)
{
cout<<"it :"<<i<<", ";
int a,b,c;
cin>>a>>b>>c;
cout<<"C:"<<c<<" ";
int ind= (b^lastAnswer)%2;
if(a==1){
cout<<"{1: ";
int* poi =arr[ind];
cout<<"$arr[ind] ad:"<<arr[ind]<<" $";
int size =0;
while(poi){poi++;size++;}
cout<<" Size at beg:"<<size<<" $";
int* n =new int[size+1];
if(size!=0)
{
for(int i=0; i<size;i++)
n[i]=poi[i];
for(int i=0; i<size+1;i++ )cout<<"i"<<i<<" "<<*poi<<" ";
delete[] poi;
}
n[size]=c;
cout<<" Elem n[size]:"<<c<<" $";
arr[ind] =n;
cout<<"E:"<<*arr[ind]<<" for index:"<<ind<<" address:"<<arr[ind]<<'\n';
}
else if(a==2)
{
cout<<"{2";
int * ak = arr[ind];
int size=0;
while(ak)
{
ak++;size++;
}
lastAnswer = *arr[c%size];
cout<<lastAnswer<<'\n';//only this cout is not debug
}
}
}
** I added added also debug code in this program.** For this input:
2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
Output is:
it :0, C:5 {1: $arr[ind] ad:0 $Size at beg:0 $Elem n[size]:5 $E:5 for index:0 ads:0x1c8d5b0
it :1, C:7 {1: $arr[ind] ad:0 $Size at beg:0 $Elem n[size]:7 $E:7 for index:1 ad:0x1c8d4d0
it :2, C:3 {1: $arr[ind] ad:0x1c8d5b0 $Size at beg:0 $Elem n[size]:3 $E:3 for index:0 ad:0x1c8d410
it :3,
Expected:
7
3
But without debug output, it doesn't print anything but shows "Runtime Error" which occurs after 3 iteration during getting from cin data I know that i should add delete or free function to prevent leak of memory but i think it would not change that i have error (or change my mind)
In advance thanks for your help :)
Aucun commentaire:
Enregistrer un commentaire