所以我需要在函数内部分配一个 int 数组。数组在调用函数之前声明(我需要在函数外部使用该数组)并且大小在函数内部确定。是否可以 ?
我一直在尝试很多事情,但到目前为止没有任何效果。
感谢您的帮助!
这是一些代码:
void fillArray(int *array)
{
int size = ...//calculate size here
allocate(array, size);
//....
}
void alloc(int * &p, int size)
{
p = new int[size];
}
int main()
{
//do stuff here
int *array = NULL;
fillArray(array);
// do stuff with the filled array
}
如果我没理解错的话,你在调用函数之前没有声明数组。您似乎声明了一个指向 int 而不是数组的指针。否则,如果您确实声明了一个数组,那么您可能无法更改其大小并在函数中分配内存。
至少有三种方法可以完成这项任务。第一个看起来像
int *f()
{
size_t n = 10;
int *p = new int[n];
return p;
}
函数的调用方式如下
int *p = f();
另一种方法是将函数的参数声明为指向 int 的指针类型。例如
void f( int **p )
{
size_t n = 10;
*p = new int[n];
}
函数可以这样调用
int *p = nullptr;
f( &p );
第三种方法是使用对指针的引用作为函数参数。例如
void f( int * &p )
{
size_t n = 10;
p = new int[n];
}
函数的调用方式如下
int *p = nullptr;
f( p );
更好的方法是使用标准类 std::vector<int>
而不是指针。例如
void f( std::vector<int> &v )
{
size_t n = 10;
v.resize( n );
}
函数可以这样调用
std::vector<int> v;
f( v );
你也可以使用像std::unique_ptr
这样的智能指针