Why the struct variable is outside the scope


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;

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

int main()
    test *test_var = NULL;
    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;

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.