Reputation: 626
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;
}
Upvotes: 0
Views: 1757
Reputation: 366
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)
Upvotes: 3
Reputation: 33579
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
.
Upvotes: 4