help with this error
I am getting this error :Access violation reading location 0xabababab.
anything wrong with this code???
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
using namespace std;
#include <string>
struct cont
{
string name;
double money;
};
int main()
{
cout << " total contributors :"<< endl;
int x;
cin >> x;
cin.get();
cont * p = new cont[x];
int i;
for (i = 0; i < x ; i++)
{
cout << "name : " << endl;
getline(cin, p->name);
cout << "money : " << endl;
cin >> p->money;
cin.get();
p = p +1;
};
p = p - (x-1);
cout << "headed patrons : " << endl;
int j = 0;
for (i = 0; i < x; i++)
{
if (p->money <= 10000)
{
cout << p->name << endl;
j++;
};
p = p+1;
};
if (j == 0)
cout << " none" << endl;
p = p - (x-1);
cout << " grand patrons : " << endl;
int k = 0;
for (i = 0; i < x; i++)
{
if (p->money > 10000)
{
cout << p->name << endl;
k++;
};
p = p+1;
};
if (k == 0)
cout << " none " << endl;
p = p -(x-1);
delete [] p;
cin.get();
cin.get();
}
|
You have:
1 2 3 4 5 6 7
|
cont * p = new cont[x];
for ( int i = 0; i < x ; i++)
{
cin >> p->money;
p = p +1;
};
p = p - (x-1);
|
The loop does increment p for 'x' times, doesn't it?
Overall, this is error-prone. Keep the pointer at the start of the array. There are alternatives:
1 2 3 4 5 6 7
|
cont * p = new cont[x];
for ( int i = 0; i < x ; ++i )
{
cin >> p[i].money;
// or
cin >> (p+i)->money;
};
|
thanx man!
Topic archived. No new replies allowed.