C ++错误:“获取临时数组的地址" [英] C++ error: "taking address of temporary array"
问题描述
我正在尝试在if语句中声明一个数组.我以这种方式编写了代码,以便一旦if-block退出,对象就保留在范围内,但是现在我遇到了一个新问题:获取临时数组的地址".我该如何用另一种方式重写它,以便为maskArray分配正确的值?
I am trying to declare an array inside an if-statement. I wrote my code this way so that the object stays in scope once the if-block exits, but now I have a new issue: "taking address of temporary array". How can I re-write this in an alternative way so that maskArray is assigned the correct values?
int* maskArray;
if(conditional==true)
maskArray = (int[9]) {0,1,0,1,-4,1,0,1,0};
推荐答案
假设您以后不打算修改maskArray
指向的内容,那么最好/最简单的解决方案是:
Assuming you aren't going to later modify what maskArray
points to, then the best/simplest solution is:
const int* maskArray;
if(conditional==true)
{
static const int myArray[9] = {0,1,0,1,-4,1,0,1,0};
maskArray = &myArray[0];
}
如果您从不打算更新数组,则静态const可以工作,但是如果要更新它,则需要一个单独的副本.这可以在堆栈或堆上创建.要在堆栈上创建它:
Static const works if you never plan to update the array, but if you're going to update it, you need a separate copy. This may be created either on the stack or on the heap. To create it on the stack:
int* maskArray;
int myArray[9] = {0,1,0,1,-4,1,0,1,0};
if(conditional==true)
{
maskArray = &myArray[0];
}
// when `myArray` goes out of scope, the pointer stored in maskArray will be useless! If a longer lifetime is needed, use the heap (see below).
要在堆上动态创建阵列的新副本,需要使用new[]
分配内存.这样做的好处是,可以在决定删除它之前将其保留有效的时间.
To dynamically create new copies of the array on the heap, you need to allocate the memory using new[]
. The advantage of this is that it can be kept around for as long as it's useful before you decide to delete it.
int* maskArray;
if(conditional==true)
{
maskArray = new int[9] {0,1,0,1,-4,1,0,1,0};
}
记住要删除,稍后再使用delete[] maskArray
!
Remember to delete is later using delete[] maskArray
!
这篇关于C ++错误:“获取临时数组的地址"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!