gpt4 book ai didi

c++ - 如何获取数组的 "change the size"[正在使用的指针]

转载 作者:行者123 更新时间:2023-11-27 23:48:02 24 4
gpt4 key购买 nike

所以我必须使用类中内置的数组来实现一个堆栈,如果“堆栈”填满,我应该增加我尝试但失败的数组的大小。所以我很好奇我需要改变什么才能完成这项工作。

class AbstractStack
{
private:
Type elements; // elements in the array
Type max;
Type *s;
public:
AbstractStack(Type num) { //CONSTRUCTOR
elements= -1;
this->max = num;
s = new Type[max];
}

/* bunch of code that does not apply to this issue


*/
void push ( Type e ) {
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
Type *temp = new Type[max + (max/2)];
for (int i = 0; i < elements+1; i++) {
temp[i] = s[i];
}
s = temp;
delete temp;
elements++;
s[elements] ;
return;
}
else {
elements++;
s[elements] = e;
}
}

当我获取这个新 s 的大小时,我得到的正确大小比以前大 1,因为这个函数仅在尝试将 1 个元素添加到完整堆栈时被调用,但是当我尝试使用 top 函数时,它只是给了我 0 然后我得到了 50 行错误代码开始于:

 *** Error in `./a.out': double free or corruption (top): 0x0000000000c53cf0 ***
======= Backtrace: =========
/lib64/libc.so.6(+0x7c619)[0x7fa34a270619]
./a.out[0x400c38]
./a.out[0x400b48]
/lib64/libc.so.6(__libc_start_main+0xf5)[0x7fa34a215c05]
./a.out[0x400979]

最佳答案

Type elements; // elements in the array  
Type max;

这些都是 int s,或 unsigned s,或 size_t s,或任何你喜欢计数的东西。他们与Type无关无论如何。

void push ( Type e ) {             
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
Type *temp = new Type[max + (max/2)];

在此之后你应该增加maxmax*3/2 .

        for (int i = 0; i < elements+1; i++) { 

循环条件应该是i < elements .您正在使用元素零和 element[elements]尚不存在。

            temp[i] = s[i]; 
}
s = temp;
delete temp;

最后两行应该是delete[] s其次是 s = temp .

        elements++;
s[elements] ;

最后两行应该是s[elements++] = e ;

        return; 

return这里是多余的。

   }
else {
elements++;
s[elements] = e;

同样,最后两行应该是 s[elements++] = e ;

   } 
}

更正和简化的版本:

int elements;
int max;

// ...
void push ( Type e ) {
if (elements + 1 == max) {
cout << "Stack at max size, WIll increase size of array and add item" << endl;
max += max/2;
Type *temp = new Type[max];
for (int i = 0; i < elements; i++) {
temp[i] = s[i];
}
delete[] s;
s = temp;
}
s[elements++] = e;
}

关于c++ - 如何获取数组的 "change the size"[正在使用的指针],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49002344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com