c ++:为类所有者#fixed创建新的指针时停止工作

时间:2016-07-18 09:50:10

标签: c++ pointers linked-list

所以问题是当程序创建指针newOwner时,它突然停止工作。

编辑感谢您的建议,代码正在运行并已修复。     #包括     #包括     #包括     #include

using namespace std;

class Owner
{
protected:
    int idNum;
    char name[255];
    char add[255];
public:
    Owner()
    {
        idNum=0;
        strcpy(name, "");
        strcpy(add, "");
    };
    Owner(int id, char *n, char *a)
    {
        idNum=id;
        strcpy(name, n);
        strcpy(add, a);
    };
    ~Owner()
    {};
    int getIdNum()
    {
        return idNum;
    };
    void setIdNum(int id)
    {
        idNum=id;
    };
    char *getName()
    {
        return name;
    };
    void setName(char *n)
    {
        strcpy(name, n);
    };
    char *getAdd()
    {
        return add;
    };
    void setAdd(char *a)
    {
        strcpy(add, a);
    };
    Owner *nextOwner=NULL;
};

Owner *headOwner=NULL;

void addOwner()
{
    char names [255], addrs[255];
    int numId;
    cout<<"variable"<<endl;
    Owner *newOwner = new Owner();
    cout<<"new pointer for newOwner"<<endl;
    Owner *copyOwner = new Owner();
    cout<<"new pointer for copyOwner"<<endl;

    newOwner -> nextOwner=NULL;
    copyOwner -> nextOwner=NULL;
    cout<<"pointing"<<endl;
    cout<<"New Boat Owner Form"<<endl;
    cout << "Enter Your Name: ";
    gets(names);
    newOwner -> setName(names);
    cout << "Enter Your Address: ";
    gets(addrs);
    newOwner -> setAdd(addrs);
    if(headOwner == NULL)
    {
        numId=1;
        newOwner -> setIdNum(numId);
        headOwner=newOwner;
    }
    else
    {
        int i;
        copyOwner=headOwner;
        while(copyOwner!=NULL)
        {
            if(i<copyOwner -> getIdNum())
            {
                i=copyOwner -> getIdNum();
                copyOwner = copyOwner->nextOwner;
            }
        }
        numId=i+1;
        copyOwner=headOwner;
        while(copyOwner->nextOwner != NULL)
        {
            copyOwner=copyOwner->nextOwner;
        }
        copyOwner->nextOwner=newOwner;
    }
}


int main()
{
    addOwner();
    return 0;
}

在程序停止工作之前,我们输出了一个输出来查找错误,&#34;变量&#34;显示输出,然后程序停止工作。无法找到错误部分。

请帮我找到错误来源。 谢谢。

2 个答案:

答案 0 :(得分:1)

您的程序在第一行失败。你不能在Owner()中执行strcpy。在这一行中,您复制名称[0]中的'\ 0'并添加[0],但此指针尚未初始化。

答案 1 :(得分:0)

Owner类声明了两个名为name和add的指针,它没有分配内存,在构造函数中,您将n指向的字符串复制到name指向的内存位置。首先为name分配内存并添加或声明为数组

not possible to test In-app billing with just a draft version