2012-11-18 40 views
3

这是我的代码Dyanamic数组类,程序运行良好,但有错误

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

只是没有得到我错在哪里。

回答

1

您的代码有几个问题。

例如,您有一个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) 
{ 
    .... 
} 
3

情况不妙:

int arr[0]; 

首先,C++不允许零大小的固定大小的数组。其次,你的代码当然需要比零大小的数组多。

无论你使用这段代码是未定义的行为(UB)。 UB包含的代码似乎“工作得很好”。

+0

我想我得到它。可能它就像阵列在内存位置被赋予连续的空间。在这里,我没有说明需要多少空间。有时间,连接的内存位置可能不是空的,并且程序显示错误。 – tehTerminator

+1

@tehTerminator对,你正在阅读和写作超出数组的范围,到你不应该的地方。 – juanchopanza

+0

@tehTerminator顺便说一句你是否试图将动态大小的数组作为练习?如果是这样,那么在引擎盖下使用'std :: vector'并不是一个真正的解决方案。 – juanchopanza

相关问题