开发者

Wrong output C++ ArrayList

When i make ArrayList with size 5 it gives wrong result but when it becomes bigger than 5 it becomes correct!

#include <iostream>
#include <string>

using namespace std;

class list
{
    typedef int ListElemtype;
private:
    ListElemtype listArray[6];
public:
    bool i开发者_开发问答nsert(ListElemtype e)
    {
        if (numberOfElements == 5) //It turns wrong result when ListArray equal 5??
        {
            cout << "Can't do the insertion" << endl;
            return false;
        } //Why it return false? I know why i but = instead of == :D
        else
        {
            listArray[numberOfElements + 1] = e;
            numberOfElements++;
            cout << "Done perfectly!" << numberOfElements << endl;
            return true;
        }
    };

    bool first(ListElemtype &e);
    bool next(ListElemtype &e);
    int numberOfElements;
    int CurrentPosition;

    void LIST ()
    {
        CurrentPosition=-1;
        numberOfElements=0;
        return;
    }
};

int main()
{
    list A;
    A.LIST();
    A.insert(10);
    A.insert(20);
    A.insert(30);
    A.insert(40);
    A.insert(50);
    A.insert(60);
    system("pause");
    return 0;
}


Arrays are indexed from zero, not from one. So listArray[numberOfElements+1]=e; should be listArray[numberOfElements]=e;. The first inserted element goes into listArray[0].


Your listArray size is 6 therefore array index would start from 0 till 5. When you have numberOfElements==5 with listArray[numberOfElements + 1] you are trying to store at index 6 which you don't have.


As you may know, C bases its arrays at 0 and not 1. Thus,

 else { listArray[numberOfElements+1]=e;

writes to the end of the array contained within list A, when numberOfElements is equal to 5 or higher.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜