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

Ron*_*nis 2 c++ int pointers reference

我有以下代码片段,它是一个数组大小调整功能的实现.它似乎是正确的,但是当我编译程序时,我得到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

这是代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

谁能帮助我?提前致谢.

Dan*_*her 8

main,你宣布

int arr[] = { 1, 2, 3, 4, 5 };
Run Code Online (Sandbox Code Playgroud)

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

而且,虽然这对于你的实现来说在技术上并不是必需的resize,因为你从来没有delete[]任何分配的内存 - 你应该修复的空间泄漏 - 你传递给的指针resize应该指向一个已new分配的内存块(你应该delete[]在其中resize).


Pet*_*ker 7

arr是一个在堆栈上分配的数组.你不能改变它的大小.如果需要可调整大小的数组,请使用指针并使用分配数组new.