C++ C++;在函数内分配动态数组

C++ C++;在函数内分配动态数组,c++,vector,pass-by-reference,dynamic-memory-allocation,function-definition,C++,Vector,Pass By Reference,Dynamic Memory Allocation,Function Definition,所以我需要在函数中分配一个int数组。数组在调用函数之前声明(我需要在函数外部使用该数组),大小在函数内部确定。可能吗? 我一直在尝试很多东西,但到目前为止什么都没用 谢谢你们的帮助,伙计们! 下面是一些代码: void fillArray(int *array) { int size = ...//calculate size here allocate(array, size); //.... } void alloc(int * &p, int size) { p

所以我需要在函数中分配一个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;
}
函数n被称为like

int *p = f();
int *p = nullptr;

f( &p );
int *p = nullptr;

f( p );
std::vector<int> v;

f( v );
另一种方法是将函数的参数声明为具有指向int的指针类型

void f( int **p )
{
    size_t n = 10;

    *p = new int[n];
}
void f( int * &p )
{
    size_t n = 10;

    p = new int[n];
}
void f( std::vector<int> &v )
{
   size_t n = 10;

   v.resize( n );
}
这个函数可以像这样调用

int *p = f();
int *p = nullptr;

f( &p );
int *p = nullptr;

f( p );
std::vector<int> v;

f( v );
第三种方法是使用对指针的引用作为函数参数。比如说

void f( int **p )
{
    size_t n = 10;

    *p = new int[n];
}
void f( int * &p )
{
    size_t n = 10;

    p = new int[n];
}
void f( std::vector<int> &v )
{
   size_t n = 10;

   v.resize( n );
}
这个函数被称为like

int *p = f();
int *p = nullptr;

f( &p );
int *p = nullptr;

f( p );
std::vector<int> v;

f( v );
更好的方法是使用标准类
std::vector
而不是指针。比如说

void f( int **p )
{
    size_t n = 10;

    *p = new int[n];
}
void f( int * &p )
{
    size_t n = 10;

    p = new int[n];
}
void f( std::vector<int> &v )
{
   size_t n = 10;

   v.resize( n );
}
void f(标准::向量&v)
{
尺寸n=10;
v、 调整大小(n);
}
这个函数可以像这样调用

int *p = f();
int *p = nullptr;

f( &p );
int *p = nullptr;

f( p );
std::vector<int> v;

f( v );
std::vector v;
f(v);

此外,您还可以使用智能指针,如
std::unique\u ptr

“在调用函数之前声明数组”-这意味着数组是已定义且已分配的。所以现在还不清楚你想要实现什么,这几乎就是我所需要的。我想我没有很好地解释我的问题。在我的主函数中有int的arrya。然后我需要调用一个函数a(),它将空数组的参数带入其中,这个函数将计算大小,然后分配并填充数组。之后,我可以在主应用程序中使用填充数组function@kevin正如我在文章中所写的,你不能定义一个空数组。您可以定义一个指针,然后在函数中为数组分配内存,并将其地址分配给指针,如我在文章中所示。我确实尝试了第一个和第二个解决方案,但没有成功。我应该如何将数组传递给应该填充它的函数?现在我已经在main中声明了数组,然后我将它传递给我的函数,然后我调用你的第二个方法来分配它,在里面function@kevinlabille我已经写过了,你不能声明一个数组并在函数中重新分配它。在我的帖子中看到函数是如何调用的。好的,第三种方法有效:)我的函数fillArray被声明为
void fillArray(int*array)
而不是
void fillArray(int*&array)
谢谢Vlad