简体   繁体   English

如何通过函数参数返回动态数组?

[英]How can I return dynamic array by function parameter?

How can I return values from my_func by parameter? 如何通过参数从my_func返回值? Application crashes during printf. 在printf期间应用程序崩溃。 I don't know why, I thought that *abc will be pointer to xxx... 我不知道为什么,我以为* abc将指向xxx ...

void my_func(int *_return)
{
    int *xxx = new int[5];
    for (int i = 0; i < 5; i++) xxx[i] = 100+i;

    _return = xxx;

    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int *abc = NULL;

    my_func(abc);
    printf("%d", abc[2]);

    return 0;
}
for (int i = 0; i <= 5; i++) xxx[i] = 100+i;  <<<< i < 5

index is till 4, as 5 would be out of bound. 索引直到4,因为5将超出范围。

To make it effective you should pass the address of pointer:- 为了使它有效,您应该传递指针的地址:

my_func(&abc);

void my_func(int**_return)

There are two ways. 有两种方法。 The first one is to use references. 第一个是使用引用。 For example 例如

void my_func(int * &a)
{
    a = new int[5];
    for (int i = 0; i < 5; i++) a[i] = 100+i;
}

and the function is called like 这个函数叫做

my_func( abc );

The second one is to use pointer to pointer. 第二个是使用指针指向指针。 For example 例如

void my_func(int **a)
{
    *a = new int[5];
    for (int i = 0; i < 5; i++) ( *a )[i] = 100+i;
}

and the function is called like 这个函数叫做

my_func( &abc );

In the both cases you should call 在这两种情况下,您都应该致电

delete [] abc;

when the array will not be needed any more. 当不再需要该数组时。

Of course you could use std::vector instead of the array 当然,您可以使用std::vector而不是数组

void my_func( std::vector<int> &v )
{
    v.reserve( 5 );
    for (int i = 0; i < 5; i++) v.push_back(  100+i );
}

and the function could be called like 该函数可以像

std::vector<int> abc;

my_func( abc );   

You have undefined behavior 您有未定义的行为

for (int i = 0; i <= 5; i++)

The only valid indexes for an array of length 5 are [0] to [4] , change your termination condition to 长度为5的数组的唯一有效索引是[0][4] ,将终止条件更改为

for (int i = 0; i < 5; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM