Unhandled exception

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
The pointer isn't pointing to anything.
Isn't it a way to create a dynamic array?
You can use it to point to (the first element of) an array, but you still need to create the array.

 
f = new int[n].
Wait, can a value type Fraction can be assigned to a value of type integer?
No, of course not. My mistake.

What I meant was:
 
f = new Fraction[n]
Oh thank you.
Now the output is correct.
Have a good day!
Topic archived. No new replies allowed.