动态数组改变大小

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:\n\n\n";
}

我希望它输出数组的大小是每次更改时的函数size.I知道这可以用向量来完成,但我想了解如何用数组来完成

我可以做些什么不同的事情来实现这一目标。

你不能: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";

但是,我不建议将此类代码放入该函数中。你让你的 class 依赖 std::cout 并没有多大好处,IMO。