【发布时间】:2012-10-02 18:00:13
【问题描述】:
我有以下一段代码,它是数组大小调整函数的实现。这似乎是正确的,但是当我编译程序时出现以下错误:
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;
}
谁能帮帮我?提前致谢。
【问题讨论】:
-
void resize( int *&arr这里去掉& -
@IonutHulub - 这会破坏函数的目的,即更改指针参数指向的数组的大小。
-
没有
*&arr这样的东西。你认为那是什么数据类型? arr 是一个指针,所以你不能在它上面调用 & ,即使你可以, * 撤消 & 的效果,因为一个用于引用,一个 if 用于取消引用。 -
@IonutHulub 实际上有。它是对指向 int 的指针的引用,它允许您更改指针及其指向的值。
-
又是这样:“数组不是 C++ 中的指针”。
标签: c++ pointers reference int