简体   繁体   中英

Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)

//Definition of pushTop()
void Staque::pushTop(const StaqueElement & value)
{
    myTop = new Staque::Node(value, myTop);
    count++;
}

//Definition of pushBottom()
void Staque::pushBottom(const StaqueElement & value)
{
    if (empty()==1)
    {
        myBottom=new Staque::Node(value);
        myTop->next=myBottom;
        count++;
    }

    myBottom->next = new Staque::Node(value);
    myBottom = myBottom->next;
    count++;
}

my pushTop function works fine but every time I try to enter an odd number I get this error

"Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)" in line 18 "myBottom->next = new Staque::Node(value);"

I am trying to add an integer to a linked list. Even numbers go to the top while odd numbers go to the bottom of the list.

Hard to tell if this is the only problem from the code you have provided, but you also need to set myBottom in the pushTop(...) method. If you don't do this, then empty() may be false, but myBottom will be invalid when calling pushBottom(...) .

Something like this:

//Definition of pushTop()
void Staque::pushTop(const StaqueElement & value)
{
    myTop = new Staque::Node(value, myTop);
    if (empty())
        myBottom = myTop;
    count++;
}

Note also that I think you need to modify myBottom(...) too, as it will add two elements if called when the stack is empty:

//Definition of pushBottom()
void Staque::pushBottom(const StaqueElement & value)
{
    if (empty())
    {
        myBottom = new Staque::Node(value);
        myTop->next = myBottom;
        count++;
    }
    else
    {
        myBottom->next = new Staque::Node(value);
        myBottom = myBottom->next;
        count++;
    }
}

An alternative might be:

//Definition of pushBottom()
void Staque::pushBottom(const StaqueElement & value)
{
    if (empty())
        pushTop(value);
    else
    {
        myBottom->next = new Staque::Node(value);
        myBottom = myBottom->next;
        count++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM