分段错误,搜索返回错误

时间:2011-10-28 20:06:30

标签: c++ visual-c++

我正在尝试设计一个地址簿,试图进行搜索,但我不断收到分段错误。我知道这意味着什么,但为什么要尝试分配正在使用的内存?为什么不搜索?

以下是代码:

class contact{

private:

    string fn="", ln="", email="", number="";

public:
    void input();
    void output();
    void setfname(string f_n);
    void setlname(string l_n);

    void setemail(string emaila);

    void setnumber(string num);
    string getfname();
    string getlname();

    string getemail();

    string getnumber();

contact();
contact(string f_n, string l_n, string emaila,string num);

};
void menu(string opt);

int search_contacts( contact contacts[],int MAX, string search);



int main(){

    string search;

    const int MAX=2;

    contact contacts[MAX];

    cout << "Enter up to " << MAX << " contacts.\n";

    for (int i = 1; i <= MAX; i++)

    {

     contacts[0].input();

    }

    [menu function goes here]

     contacts[0].output();

return 0;

}
 int search_contacts(contact contacts[],int size, string search)

{
 cout << "Search contact by LastName:____  ";

 cin >> search;

  bool lookup = false;

  for(int index=0;index<size;index++)

    {

      if(contacts[index].getlname() == search)

     { 

      lookup = true;

      cout<<"Result found "<<endl;

      break;

    }

     }

if(!lookup)

cout<<"no record found"<<endl;

}

void menu(string opt){
 string search;
contact contacts[0];
const int MAX = 2;

[show menu msg...here]

     cin>>opt;

// do this if the option selected is search 

if(opt=="search")

  {

    search_contacts(contacts, MAX, search);

}
[more menu code]
}
void contact::input()
{

cout<<"fn and ln separate by a space: ";

cin>>fn>>ln;

cout<<"email: ";

cin>>email;

cout<<"phone number: ";

cin>>number;

}

void contact::output()
{
[output code... goes here];

}
string contact::getlname()
{

return ln;

}

[functions that delegates the variables...goes here]

2 个答案:

答案 0 :(得分:1)

如评论中所述,您应该学习如何使用调试器来确定分割错误的原因。

在我看来,您正在尝试对不存在的联系人进行操作。我在menu()中看到了一个零长度数组,但我看不到您在main()中创建的menu()函数与您的搜索函数之间的联系方式。

如果您尝试对未初始化的对象执行操作,您会看到类似的分段错误。

答案 1 :(得分:0)

您无法使用==进行字符串比较,当您选择“搜索”并尝试查找匹配的名称时,您已完成此操作。 http://www.cplusplus.com/reference/clibrary/cstring/strcmp/