C ++在函数内部分配动态数组 [英] C++ Allocate dynamic array inside a function

查看:160
本文介绍了C ++在函数内部分配动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要在一个函数内分配一个int数组。在调用函数之前声明数组(我需要在函数外部使用该数组),并且在函数内部确定大小。可能吗 ?
我一直在尝试很多事情,但到目前为止没有任何效果。

so I need to allocate an array of int inside a function. The array is declared before calling the function (I need to use that array outside the function) and the size is determined inside the function. Is it possible ? I have been trying a lot of thing but nothing worked so far.

感谢您的帮助!
这是一些代码:

Thanks for your help guys ! Here is some code :

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而不是数组的指针。否则,如果确实声明了数组,则不能更改其大小并在函数中分配内存。

If I have understood correctly you did not declare an array before calling the function. It seems that you declared a pointer to int instead of an array. Otherwise if you indeed declared an array then you may not change its size and allocate memory in the function.

至少有三种方法可以执行此任务。第一个看起来像

There are at least three approaches to do the task. The first one looks like

int *f()
{
    size_t n = 10;

    int *p = new int[n];

    return p;
}

函数称为

int *p = f();

另一种方法是将函数的参数声明为具有指向int的指针的类型。例如

The other approach is to declare a parameter of the function as having type of pointer to pointer to int. For example

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

    *p = new int[n];
}

函数可以像

int *p = nullptr;

f( &p );

第三种方法是使用对指针的引用作为函数参数。例如,

The third approach is to use reference to pointer as the function parameter. For example

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

    p = new int[n];
}

该函数的名称类似于

int *p = nullptr;

f( p );

更好的方法是使用标准类 std :: vector< int> 而不是指针。例如

The better way is to use standard class std::vector<int> instead of a pointer. For example

void f( std::vector<int> &v )
{
   size_t n = 10;

   v.resize( n );
}

函数可以像

std::vector<int> v;

f( v );

此外,您还可以使用像 std :: unique_ptr

Also you could use a smart pointer like std::unique_ptr

这篇关于C ++在函数内部分配动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆