0

In the below code, Why i couldn't able to access test_var from main? My assumptions are that new allocates memory in heap, so the lifetime is till the end of the main, or till you explicitly delete it. But when i try to access test_var, i get exception.

typedef struct test{
    int a;
    string str;
}test;

void fun1(test* test_var)
{
    test_var = new test[2];
    test_var[0].a=1;
    test_var[0].str='a';
    test_var[1].a = 2;
    test_var[1].str = 'b';
    return;
}

int main()
{
    test *test_var = NULL;
    fun1(test_var);
    cout<<test_var[0].str;
    delete test_var;            
    return 1;
}
0

2 Answers 2

4

Because test_var is local to fun1, and the assignment

test_var = new test[2];

only has effect within the function.

You need

void fun1(test** test_var)
{
   *test_var = new test[2];
   ...
}

and in main:

test *test_var = NULL;
fun1(&test_var);

P. S. This isn't really C++ code. Raw pointers manipulation is dangerous and should be avoided. C++ has much cleaner mechanisms for doing what you're trying to do. See std::vector, std::shared_ptr.

Sign up to request clarification or add additional context in comments.

Comments

3

It is because in function fun1, test_var is a local variable.

void fun1(test* test_var)

Hence, any modification done in fun1 is done on local variable.

You need to do:

void fun1(test*& test_var)

13 Comments

That'll work, but using a pointer to pointer instead of reference to pointer (as my answer suggests) is a more conventional way.
@VioletGiraffe In C, maybe. But the question is tagged C++.
I think the least confusing option is test* fun1();, returning the pointer.
@juanchopanza: the question is tagged C++, but involves raw pointers which is not the C++ way. Your point?
The choice of pointer-to-pointer vs reference-to-pointer is divisive... the FAQ Lite encourages references, but many people and company coding standard encourage pointers (e.g. Google (me!)). The arguments for either side tend to depend on how common certain things are in the overall body of code, so are somewhat application/library-domain specific, and the best fit for one community of programmers may not suit another. It's not worth arguing about.
|

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.