【问题标题】:Dyanamic Array Class, Program runs well but with Error动态数组类,程序运行良好但出现错误
【发布时间】:2012-11-18 16:02:37
【问题描述】:

这是我的代码

#ifndef INTLIST_H_INCLUDED
#define INTLIST_H_INCLUDED
#include <iostream>
using namespace std;

class intList
{
    int upper_bound;
    int arr[0];
    public:
        intList(){ arr[0] = 0; upper_bound = 0; }
        void append(int x);
        void sort();
        friend ostream & operator << (ostream &, intList&);
        inline int len(){ return upper_bound; }
        inline int &operator [](int x){ return arr[x]; }
    private:
        void increment(int *a, int &l);
        void swap(int &a, int &b);
};

void intList::swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

void intList::increment(int *a, int &b)
{
    b++;
    a[b] = 0;
}

void intList::append(int num)
{
    arr[upper_bound] = num;
    increment(arr, upper_bound);
}

void intList::sort()
{
    for(int i = 0; i < upper_bound; i++)
    {
        int minLoc = i;
        for(int j = i+1; j<upper_bound; j++)
        {
            if(arr[j] < arr[minLoc])
                minLoc = j;
        }
        if(minLoc != i)
            swap(arr[i], arr[minLoc]);
    }
}

ostream& operator << (ostream & dout, intList &a)
{
    dout << "[ ";
    for(int i = 0; i<a.upper_bound-1; i++)
        dout << a.arr[i] << ", ";
    dout << a.arr[a.upper_bound-1] << " ]";

    return dout;
}

#endif // INTLIST_H_INCLUDED

《守则》完美地完成了它的工作。但最后程序崩溃了。给出一些错误,例如 进程返回 -1073741819 (0xC0000005) 执行时间:几秒。

只是不知道我哪里错了。

【问题讨论】:

    标签: c++


    【解决方案1】:

    这看起来很糟糕:

    int arr[0];
    

    首先,C++ 不允许零大小的固定大小数组。其次,您的代码当然需要的不仅仅是一个零大小的数组。

    无论您如何使用此代码,都是未定义行为 (UB)。 UB 包含看似“运行良好”的代码。

    【讨论】:

    • 我想我明白了。可能就像数组在内存位置中被赋予顺序空间一样。在这里,我并没有确切地声明需要多少空间。有时连接的内存位置可能不是空的,程序会显示错误。
    • @tehTerminator 对,你正在读写超出数组的边界,到你不应该的地方。
    • @tehTerminator 顺便说一句,您是否尝试实现一个动态大小的数组作为练习?如果是这样,那么在后台使用 std::vector 并不是真正的解决方案。
    • 那我该怎么做。我的书没有关于向量的任何内容。我虽然可能我可以创建一些类似上面代码的东西。
    • @tehTerminator 我不知道“书”是什么,但我想说的是,如果你在做一个练习,并且目标是实现一个动态大小的数组,那么使用向量有点作弊,因为它是专业设计和实现的动态大小的数组类。另一方面,如果你只是需要这个东西来做别的事情,那么就使用向量。
    【解决方案2】:

    您的代码有几个问题。

    例如,您有一个大小为 0 的固定数组。如果您想要一个动态可增长的数组,您可以使用std::vector:您可以使用push_back() 方法在向量末尾添加新项目(动态调整其大小):

    #include <vector>
    
    // Start with an empty vector
    std::vector<int> v;
    
    // Add some items to it
    v.push_back(10);
    v.push_back(20);
    ....
    

    还要注意,在头文件中插入using namespace std; 是不好的。通过这种方式,您会使用 STL 类污染全局命名空间,这很糟糕。只需在头文件中使用std:: 前缀

    此外,如果您想将类内容打印到输出流,您可能希望将类作为 const 引用,因为类的实例是输入参数(您 观察他们并将他们的内容打印到流中):

    std::ostream& operator<<(std::ostream& os, const IntList& a)
    {
       ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多