访问结构时出现分段错误

Segmentation fault when accessing a structure

本文关键字:分段 错误 结构 访问      更新时间:2023-10-16

程序一直工作到检查用户输入的名称。当你在从一个充满客户信息的文件中导入的结构数组中输入你想要搜索的名称时,它会返回分段故障核心转储。这让我很困惑。

#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
        char name[50];
        string email;
        long int phone;
        string address;
};

#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];

void readIn(ifstream& file){
        int i=0;
        while(!file.eof()){
                file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
        }
}
void getAccount(){
        char userPick[50];
        char streamName[50];
        cout << " What account will we  be using? " << endl;
        cin.getline(streamName, 50);
        for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
                if( strcmp(account[i].name, streamName)==0){
                        cout << "nn FOUND IT!! nn";
                        cout << account[i].name << "n" << account[i].email << "n" << account[i].phone << "n" << account[i].address << endl;
                }
        }
}
int main(){
        ifstream file;
        file.open("2.dat"); //opens data account records text
        readIn(file);
        getAccount();
        delete account;
        return 0;
}

循环不断将所有内容读入数组的初始元素:

while(!file.eof()){
    file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}  

因为CCD_ 1的值从不递增。您可以将其转换为for循环,如下所示:

for (count = 0 ; count < MAX && !file.eof() ; count++) {
    file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}

注意,我将i更改为count:

AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;

这将帮助您解决另一个问题——确定数组何时在getAccount函数中结束。目前,你假设记录总是在那里,所以外循环继续。现在你有了count,你可以这样改变循环:

for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
    if( strcmp(account[i].name, streamName)==0){
        cout << "nn FOUND IT!! nn";
        cout << account[i].name << "n" << account[i].email << "n" << account[i].phone << "n" << account[i].address << endl;
        break;
    }
}
if (i == count) {
    cout << "Not found." << endl;
}