Mar 4, 2019 at 11:50am Mar 4, 2019 at 11:50am UTC
I have a code like this:
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
#include <iostream>
#include <fstream>
using namespace std;
struct Fraction
{
int nu, de;
};
void Enter(Fraction *&f, int &n)
{
cout << "Enter the number of elements: " ;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "Enter fraction number " << i + 1 << ":\n" ;
cin >> f[i].nu;
cin >> f[i].de;
}
}
void Output(Fraction *&f, int &n)
{
cout << "Elements:\n" ;
for (int i = 0; i < n; i++)
{
cout << f[i].nu << "/" << f[i].de << endl;
}
}
void Write(Fraction *&f, int n)
{
ofstream fout("output.bin" , ofstream::binary);
if (!fout.is_open())
{
cout << "Can not create output.bin" << endl;
}
fout.write((char *)&n, sizeof (int ));
for (int i = 0; i < n; i++)
{
fout.write((char *)&f[i], sizeof (Fraction));
}
fout.close();
cout << "Completely" << endl;
}
int main()
{
Fraction *a;
int n;
Enter(a, n);
Output(a, n);
}
This will let the user enter some fractions and then save them into a file name "output.bin". However, at the line
cin >> f[i].nu;
, the compiler told me:
Unhandled exception at 0x0F75591C (msvcp140d.dll) in ex03.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC. occurred
(ex03.exe is the executed file from my solution).
What happened?
Last edited on Mar 4, 2019 at 12:04pm Mar 4, 2019 at 12:04pm UTC
Mar 4, 2019 at 12:06pm Mar 4, 2019 at 12:06pm UTC
The pointer isn't pointing to anything.
Mar 4, 2019 at 12:15pm Mar 4, 2019 at 12:15pm UTC
Isn't it a way to create a dynamic array?
Mar 4, 2019 at 5:03pm Mar 4, 2019 at 5:03pm UTC
Wait, can a value type Fraction can be assigned to a value of type integer?
Mar 5, 2019 at 6:08am Mar 5, 2019 at 6:08am UTC
Oh thank you.
Now the output is correct.
Have a good day!