引用指向 int 的指针会导致错误

reference to pointer to int causes error

本文关键字:错误 指针 int 引用      更新时间:2023-10-16

我有以下一段代码,它是数组大小调整函数的实现。这似乎是正确的,但是当我编译程序时,我收到以下错误:

g++ -Wall -o "resizing_arrays" "resizing_arrays.cpp" (in directory: /home/aristofanis/Desktop/coursera-impl)
resizing_arrays.cpp: In function ‘int main()’:
resizing_arrays.cpp:37: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
resizing_arrays.cpp:39: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
resizing_arrays.cpp:41: error: invalid initialization of non-const reference of type ‘int*&’ from a temporary of type ‘int*’
resizing_arrays.cpp:7: error: in passing argument 1 of ‘void resize(int*&, int, int, int)’
Compilation failed.

这是代码:

int N=5;
void resize( int *&arr, int N, int newCap, int initial=0 ) { // line 7
  N = newCap;
  int *tmp = new int[ newCap ];
  for( int i=0; i<N; ++i ) {
    tmp[ i ] = arr[ i ];
  }
  if( newCap > N ) {
    for( int i=N; i<newCap; ++i ) {
      tmp[ i ] = initial;
    }
  }
  arr = new int[ newCap ];
  for( int i=0; i<newCap; ++i ) {
    arr[ i ] = tmp[ i ];
  }
}
void print( int *arr, int N ) {
  for( int i=0; i<N; ++i ) {
    cout << arr[ i ];
    if( i != N-1 ) cout << " ";
  }
}
int main() {
  int arr[] = { 1, 2, 3, 4, 5 };
  print( arr, N );
  resize( arr, N, 5, 6 ); // line 37
  print( arr, N);
  resize( arr, N, 10, 1 ); // line 39
  print( arr, N );
  resize( arr, N, 3 ); // line 41
  print ( arr, N );
  return 0;
}

谁能帮我?提前谢谢。

main中,你声明

int arr[] = { 1, 2, 3, 4, 5 };

一个普通的数组,而不是一个int*,这是你必须传递给resize的。

而且,尽管这在技术上对于您的resize实现不是必需的,但由于您从未在那里delete[]任何分配的内存 - 您应该修复空间泄漏 - 您传递给resize的指针应指向new分配的内存块(您应该delete[] resize)。

arr是在

堆栈上分配的数组。您无法更改其大小。如果需要可调整大小的数组,请使用指针并使用 new 分配数组。

数组不是指针。特别是,数组保持不变。你不能移动它。在使用 poibter 的上下文中,您还将创建内存泄漏和越界访问。

要创建一个可调整大小的数组,您需要维护一个指针,该指针最初是从数组中元素的副本设置的。就个人而言,我不会打扰和使用std::vector<int>(除非我正在开发自己的标准C++库并实现std::vector<T>)。

您收到特定错误的原因是arr将衰减为使用的临时int*。然后尝试将非常量引用(参数)绑定到临时引用,这是非法的。看这里:

为什么非常量引用不能绑定到临时对象?

当你说int&时,这意味着一个int变量,我可以改变它的值,同样当你说int*&时,它意味着一个int*变量,我可以改变它的值。 现在看看你的代码,你能改变arr的值吗? 说arr = new int[10]合法吗? 你看这是不合法的, 在术语C++它不是一个Lvalue(它不能位于相等运算符的左侧),并且所有非常量引用都必须Lvalue