01/10/2018, 14:54
Lỗi "...Access violation reading location 0x00000004" khi đọc file trong C++
Cho em hỏi, em có đoạn code ntn, em muốn đọc dữ liệu từ a.txt lưu vào mảng phân số rồi in ra màn hình, nếu để hàm xuatMangPS() trong hàm docPhanSo() thì in ra màn hình bình thường, nhưng để trong main() thì lại lỗi, em chẳng biết gg lỗi này thế nào, nên đăng lên đây mong mn giúp.
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct PHANSO{
int tu, mau;
};
ostream &operator <<(ostream &output, PHANSO &ps){
output << ps.tu << "/" << ps.mau;
return output;
}
istream &operator >>(istream &input, PHANSO &ps){
input >> ps.tu >> ps.mau;
return input;
}
void xuatMangPS(PHANSO *ps, int n){
for (int i = 0; i < n; i++){
cout << ps[i] << endl;
}
}
void docPhanSo(istream &input, PHANSO *ps, int &n){
char *c;
c = new char[4];
input.getline(c,4);
n = *c - '0';
ps = new PHANSO[n];
int i = 0;
while (input.getline(c,4)){
ps[i].tu = c[0] - '0';
ps[i++].mau = c[2] - '0';
}
delete []c;
}
int main(){
PHANSO *ps = NULL;
int n;
ifstream file("a.txt");
if (!file){
cout << "Mo file loi" << endl;
}else{
docPhanSo(file, ps, n);
xuatMangPS(ps, n);
delete[]ps;
}
system("pause");
return 0;
}
Đây là lỗi khi để xuatMangPS() trong main()
Đây là kết quả khi để xuatMangPS() trong docPhanSo()

Em cảm ơn
Bài liên quan
HI Huynh Tan Thanh.
Bạn gg từ kháo “debug chương trình C++ VS”