c++ - 动态数组类,程序运行良好但出现错误

标签 c++

这是我的代码

#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) 执行时间:几秒。

只是没明白我哪里出错了。

最佳答案

这看起来很糟糕:

int arr[0];

首先,C++ 不允许大小为零的固定大小数组。其次,您的代码肯定需要不止一个零大小的数组。

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

关于c++ - 动态数组类,程序运行良好但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441796/

相关文章:

c++ - 使用 SIMD 范例在 256 位 vector 上应用给定函数

c++ - 无法在 Windows 应用商店应用程序 8.1 中使用 fstream 创建文件

c++ - 在 C++/CLI 代码中包含的代码中使用 <thread>。寻找更好的解决方案

c++ - 可以在 Internet 上而不是在 LAN 集群内分发 MPI (C++) 程序吗?

c++ - 有人请解释一下它的行为是什么?

c++ - 为什么 N3421 不提供 noexcept 限定词?

c++ - 使用 rocksdb::Iterator 和 Column Family 不起作用

c++ - 如果函数的返回值将用作右值引用而不是左值,是否有办法使函数具有不同的行为?

c++ - 多重定义错误 : How to declare a reference in a header file?

c++ - 创建一个返回指向类模板对象的共享指针的函数