在 CodeBlocks 中对此进行编码,该程序不断出现段错误。有人可以帮忙吗?
#include <string>
#include <iostream>
#include <sstream>
#include "include/hugeint.h"
using namespace std;
int main(int argc, char *argv[])
{
HugeInt h("123");
return 0;
}
我的 HugeInt 类(相关的),将非常大的整数存储为整数数组
class HugeInt
{
public:
HugeInt(string);
private:
DynArray dyn;
//HugeInt& reverse();
int size;
};
HugeInt::HugeInt(string input)
{
string digits = input;
for(unsigned int i = 0; i < digits.length(); i++){
dyn.add(digits.at(i) - 48);
}
size = dyn.size();
}
我的动态数组整数类
class DynArray
{
public:
DynArray();
~DynArray();
private:
int length;
int *arr; //points to this array
int nextIndex;
};
DynArray::DynArray() {
arr = new int[10];
for (int i = 0; i < 10; i++)
arr[i] = 0;
length = 10;
nextIndex = 0; }
DynArray::~DynArray()
{
delete [] arr;
}
int DynArray::size(){
return nextIndex;
}
void DynArray::add(int val) {
int *newArr;
if (nextIndex == length) {
length = length + 10;
newArr = new int[length];
for (int i = 0; i < nextIndex; i++)
newArr[i] = arr[i];
for (int j = nextIndex; j < length; j++)
newArr[j] = 0;
delete [] arr;
arr = newArr;
}
arr[nextIndex++] = val;
}
编辑:我评论了 delete [] arr; 出来,它仍然段错误:/
Edit2:好的,如果 main 如下,则代码可以工作。谁能解释一下为什么?
#include <string>
#include <iostream>
#include <sstream>
#include "include/hugeint.h"
using namespace std;
int main(int argc, char *argv[])
{
string in = "1234";
HugeInt h(in);
return 0;
}