a Unhandled exception :Access violation reading location 0x00000004
I get this error in the debugging mode when i first encounter the marked line in the code below
#include<fstream>
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
int main()
{int t,i,j,k,n,g[100],w[100],opp[100];
float rpi[100],wp[100],owp[100],oowp[100];
char s[100][100];
ifstream ip; ip.open("A-small-practice.in"); ofstream op; op.open("A_out.in");
ip>>t;
for(i=0;i<t;i++)
{ ip>>n;
memset(g,0,sizeof(g));
memset(w,0,sizeof(w));
memset(op,0,sizeof(op));
memset(rpi,0,sizeof(rpi));
memset(wp,0,sizeof(wp));
memset(owp,0,sizeof(owp));
memset(oowp,0,sizeof(oowp));
memset(s,'.',sizeof(s));
for(j=0;j<n;j++)
{for(k=0;k<n;k++)
{ip>>s[j][k]; //<--------------------the error occurs here
if(s[j][k]=='0')
g[j]++;
if(s[j][k]=='1')
{g[j]++;w[j]++;}
}
wp[j]=w[j]/g[j];
}
for(j=0;j<n;j++)
{for(k=0;k<n;k++)
if(j!=k && s[k][j]!='.')
{owp[j]+=(wp[k]*g[k]-s[k][j])/(g[k]-1);
opp[j]++;
}
owp[j]/=opp[j];
}
for(j=0;j<n;j++)
开发者_如何学编程 {for(k=0;k<n;k++)
{if(j!=k && s[k][j]!='.')
oowp[j]+=owp[k];
}
oowp[j]/=opp[j];
}
op<<"Case #"<<i+1<<": \n";
for(j=0;j<n;j++)
{rpi[j]=(0.25*wp[j]) + (0.5*owp[j]) +(0.25*oowp[j]);
op<<rpi[j]<<"\n";
}
}
return 0;
}
the debugger breaks at this code segment when stepped in. The loops and logic the value size is all correct i don't know where the overflow is ocurring..is there any other cause for this?
class _Sentry_base
{ // stores thread lock and reference to input stream
public:
__CLR_OR_THIS_CALL _Sentry_base(_Myt& _Istr)
: _Myistr(_Istr)
{ // lock the stream buffer, if there
if (_Myistr.rdbuf() != 0)//<-------------break points here
_Myistr.rdbuf()->_Lock();
}
You don't need to use memset
for the 1D arrays. For example
int g[100] = {0};
will work.
For the 2D array, loop through using a for loop and set each element to '.'
, or stick with the memset
for that step.
In terms of your actual problem, you may need to use ip.get()
to read character by character instead.
精彩评论