Why the struct variable is outside the scope

advertisements

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;
}


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.