1

How can I return values from my_func by parameter? Application crashes during printf. I don't know why, I thought that *abc will be pointer to 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;
}
2
  • 1
    Make it std::vector<int> my_func() and be happy Commented Dec 14, 2014 at 16:00
  • Change every occurrence of _return to *_return (yes, even where you already have one * preceding it). In addition, change my_func(abc) to my_func(&abc). Commented Dec 14, 2014 at 16:10

3 Answers 3

1

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

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 );   
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I was looking for that solution, thank You! It's working, I used the second solution...
You gave me very detailed solutions, thank You again... especially for the pointer-to-pointer... have a nice day! :)
1
for (int i = 0; i <= 5; i++) xxx[i] = 100+i;  <<<< i < 5

index is till 4, as 5 would be out of bound.

To make it effective you should pass the address of pointer:-

my_func(&abc);

void my_func(int**_return)

1 Comment

@mateusz_s: Also change _return = xxx to *_return = xxx.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.