引用指向 int 的指针会导致错误
reference to pointer to int causes error
我有以下一段代码,它是数组大小调整函数的实现。这似乎是正确的,但是当我编译程序时,我收到以下错误:
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
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 运行几次后合并段错误C++(指针算术)
- LinkedList实现C 错误指针间接
- 虚幻引擎 4.18.0,VS2017,不允许指向不完整类类型的错误指针
- Xcode 错误:指针和双精度之间的比较
- 未分配正在释放的本机node.js插件错误指针
- 错误指针:解析令牌时无法计算表达式
- C++-va_list错误指针
- 为什么我收到错误" (指针的名称)不是模板)?
- mmap 错误:分段错误/指针无效错误
- C++ Winsock2 错误指针断点触发
- C++ 代码中的错误指针错误
- 数组错误指针上的增量运算符
- MAKEINTRESOURCE 返回资源 ID 的错误指针
- 分段错误C++指针
- 段错误指针
- C++ 错误 :: 指针数组的EXC_BAD_ACCESS
- 通过模糊 mat 从 std::vector: <int>cv::Exception 中获取错误指针
- 正在解决编译器错误:指针可能未初始化