动态数组更改大小
dynamic array change size
我创建了这个函数来更改动态数组的大小
size = 4; //this is what size is in my code
int *list = new int[size] // this is what list
void dynArray::doubleSize( )
{
int *temparray;
int currentsize = size;
int newsize = currentsize * 2;
temparray = new int[newsize];
for (int i = 0 ; i < newsize;i++)
{
temparray[i] = list[i];
}
size = newsize;
delete [] list;
list = new int[size];
list = temparray;
// this it help see if i made any changes
cout << sizeof(temparray) << "temp size:n";
cout << sizeof(list) << "list size:n";
cout << size << "new size:nnn";
}
我希望它每次更改大小时输出数组的大小是函数。我知道这可以用向量来完成,但我想了解如何用数组做到这一点
我能做些什么来实现这一目标。
您不能:C++ 标准不提供访问动态数组维度的机制。 如果你想知道它们,你必须在创建数组时记录它们,然后查看你设置的变量(就像你在程序结束时有size
挂在打印上一样。
代码中的问题:
问题1
以下for
循环使用越界索引访问list
。list
中的元素数是size
,而不是newSize
。
for (int i = 0 ; i < newsize;i++)
{
temparray[i] = list[i];
}
您需要将条件更改为 i < size;
。
然后,您需要弄清楚如何初始化temparray
中的其余项目。
问题2
以下行会导致内存泄漏。
list = new int[size];
list = temparray;
您使用 new
分配内存,并立即丢失第二行中的指针。
回答您的问题
要打印新尺寸,您可以使用:
cout << "new size: " << size << "n";
但是,我不建议在该函数中放置此类代码。IMO,你让你的班级依赖于std::cout
没有多大好处。
相关文章:
- std::向量与传递值的动态数组
- 将数组动态分配到具有指针参数的函数中
- 我可以以某种方式使我的矢量/数组动态更改装置数量吗?
- 使用 new: "potentially uninitialized pointer"将对象数组动态分配给指针
- 为什么C 没有方便的方式来为多维数组动态分配内存
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- c++中的数组动态内存分配
- 多维数组动态分配的内存图
- 如何在 c++ 中使用 2-D 固定数组为 4-D 数组动态分配内存
- C++ 我在数组/动态内存方面遇到了一些问题
- C++ 中从数组动态强制转换
- C++中高维数组动态内存分配的正确方法.
- 从 C++ 结构中包含的指针数组动态分配和访问内存
- 对象数组动态内存分配
- 为二维数组动态分配内存时出错
- 如何将2d数组动态分配给结构
- 为结构数组c++动态分配内存
- 将数组动态添加到多维数组
- 类中的类数组-动态数组(c++)有问题
- 分配对象数组动态冻结