动态数组更改大小

dynamic array change size

本文关键字:数组 动态      更新时间:2023-10-16

我创建了这个函数来更改动态数组的大小

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循环使用越界索引访问listlist中的元素数是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没有多大好处。