Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference to pointer to int causes error

I have the following piece of code, which is an implementation of an array resizing function. It seems to be correct, but when I compile the program I get the following errors:

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.

Here is the code:

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;
}

Could anyone help me? Thanks in advance.

like image 242
Rontogiannis Aristofanis Avatar asked Jul 16 '26 02:07

Rontogiannis Aristofanis


1 Answers

In main, you declare

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

an ordinary array, not an int*, which is what you would have to pass to resize.

And, although that is not technically necessary for your implementation of resize, since you never delete[] any allocated memory there - a space leak you should fix -, the pointer you pass to resize should point to a new-allocated memory block (that you should delete[] in resize).

like image 50
Daniel Fischer Avatar answered Jul 17 '26 16:07

Daniel Fischer