I want to change/re allocate given array as argument to a function. I have the following function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void changeArray(int*& a)
{
a = newint [3];
a[0] = -1;
a[1] = -2;
a[3] = -3;
}
int main()
{
int a [] = {10,10,10,10,10,11,10,11};
changeArray(a);
system("pause");
visual studio compiler doesnt compile it it says:
Error 1 error C2664: 'changeArray' : cannot convert parameter 1 from 'int [8]' to 'int *&' g:\cppprojects\cahpter9\driver.cpp 69 1 Cahpter9
2 IntelliSense: a reference of type "int *&" (not const-qualified) cannot be initialized with a value of type "int [8]" g:\cppprojects\cahpter9\driver.cpp 69 14 Cahpter9
where g:\cppprojects\cahpter9\driver.cpp is my "main" function location.
The error message showed clearly enough that arrays are not pointers. You declared the parameter as reference to pointer int * & and were trying to pass an argument as an array and the compiler reported that the reference to pointer is not the same as the reference to array
#include <iostream>
void foo( int*&& ) { std::cout << "foo( int*&& )\n" ; }
void foo( int&& ) { std::cout << "foo( int&& )\n" ; }
void bar( int* const& ) { std::cout << "foo( int* const& )\n" ; }
void bar( constint& ) { std::cout << "bar( const int& )\n" ; }
void baz( int*& ) { std::cout << "baz( int*& )\n" ; }
void baz( int& ) { std::cout << "baz( int& )\n" ; }
void foobar( int* ) { std::cout << "foobar( int* )\n" ; }
void foobar( int ) { std::cout << "foobar( int )\n" ; }
int main()
{
int a [] = {10,10,10,10,10,11,10,11};
short s = 23 ;
foo(a); // fine a => rvalue of type int*; passed by reference to rvalue
foo(s); // fine s => rvalue of type int; passed by reference to rvalue
bar(a) ; // fine a => rvalue of type int*; passed by reference to const
bar(s) ; // fine s => rvalue of type int; passed by reference to const
// baz(a) ; // *** error, can't pass rvalue as reference to non-const lvalue
//baz(s) ; // *** error, can't pass rvalue as reference to non-const lvalue
foobar(a) ; // fine a => rvalue of type int*; passed by value (pass a copy of the rvalue)
foobar(s) ; // fine s => rvalue of type int; passed by value (pass a copy of the rvalue)
}