ast*_*123 0 c++ arrays segmentation-fault data-structures
我正在尝试实现一个无界数组:什么是无界数组?
本页更多细节:http: //www.cs.cmu.edu/~fp/courses/15122-s11/lectures/12-ubarrays.pdf
这是代码:
#include <iostream>
#include <cstdlib>
using namespace std;
class UBArray
{
public:
int *arr, *arrN, j, *pos; //Initial array is arr. The position of arr is stored in pos. arrN is the new array created when size = limit.
int size, limit; //size is the current size of the array and limit is the total size available untill a new array is created.
UBArray()
{
size = 0;
limit = 10;
arr = new int[10];
pos = arr;
}
private:
void increment()
{
// New array arrN is created and then the values in the old arrays is put into the new array.
// Limit is increased by 10 - this is the extra space the new array contributres.
// pos which carries the address of the current array now carries the address of the new array.
// Later when a new array is created its address will be on the heap which is empty. This address is replace the address stored
// in the arrN. The older array can still be accessed for the array updation process by using the variable pos.
// IMPORTANT: I had initially tried to delete the older array to space space but while trying to debug the segmentation fault, I have
// removed it. I will be adding it again once the error has been fixed.
arrN = new int[size + 10];
for (j = 0; j < size; j++)
{
arrN[j] = pos[j];
}
limit = limit + 10;
pos = arrN;
}
public:
void push(int n)
{
if (size<limit)
{
size++;
pos[size-1]=n;
}
else
{
increment();
push(n);
}
}
int pop()
{
int p = pos[size-1];
size--;
return p;
}
};
int main()
{
UBArray array;
int num;
cout << "Enter 36 elements: ";
for (int k = 0; k<36; k++)
{
cin >> num;
array.push(num);
}
cout << endl << "The last element is : " << array.pop();
}
Run Code Online (Sandbox Code Playgroud)
我试图在代码中给出评论,以使读者理解它.我在这里复制一些内容:
初始数组是arr
.arr的位置存储在pos
.arrN
是size
= 时创建的新数组limit
.
size
是数组的当前大小,limit
是创建新数组之前可用的总大小.
arrN
创建新数组,然后将旧数组中的值放入新数组中.
Limit
增加10 - 这是新阵列贡献的额外空间.
pos
它携带当前数组的地址,现在携带新数组的地址.
稍后当创建一个新数组时,它的地址将在空的堆上.该地址被替换为地址arrN
.通过使用pos
将由旧值更新的变量复制到新变量,仍可以访问旧数组以进行数组更新过程.
我在执行期间遇到分段错误.我曾尝试使用cout语句来调试代码,但它似乎真的令人困惑.我可以在increment
方法内部看到for循环内外的循环.我无法弄清楚.任何帮助表示赞赏.
更新:正如jrok所指出的,我改变了代码并且seg故障消失了.但是我在创建第3个阵列时又遇到了seg故障.
更新2现在一切都已修复.谢谢.
arr = new int(10*sizeof(int));
Run Code Online (Sandbox Code Playgroud)
这创建了一个单一的int
,初始化为的值10*sizeof(int)
.你在这个语句之后写的循环超出了界限,这是分段错误的原因.
你想要的是阵列形式new
:
arr = new int[10]; // note 10 only, new expression knows the size
// of the type it allocates
Run Code Online (Sandbox Code Playgroud)
请注意,当您将指向新数组的指针指向旧数组的指针时,您将丢失它的句柄并创建内存泄漏:
int* arr = new int[10];
int* new_arr = new int[20];
arr = new_arr; // original array at arr has leaked
Run Code Online (Sandbox Code Playgroud)
你需要delete[] arr
在重新分配它之前.另外,我认为没有使用第三个(pos
)指针.arrN
就此而言,甚至都没有.一个人会这样做.在内部创建一个本地指针,increment
并arr
在完成取消分配旧数组时将其指定给它.
最后,人们在评论中告诉你的内容,除非这是一个学习练习,否则不要试图重新发明轮子并使用std::vector
.