Null pointer after allocating in function

后端 未结 2 1866
温柔的废话
温柔的废话 2020-12-21 22:38

I have problem with pointer in C++. I declared pointer data and initializing it in function, but after my program left function data pointer is NULL. I provide outp

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 22:49

    You define a pointer and don't assign anything to it:

    Data *data;
    

    By definition *data can point to anything "it wants". So, the BEFORE and AFTER values are just random adresses.

    However, in your function1 the first thing you do is allocate memory for a new Data object, and overwrite your existing pointer with that, so obviously your value for DURING is different and the only one that's meaningful among the three.

    Alas, since you pass your pointer by value, you toss everything you do in function1 away once it ends.

    I assume, what you want is move that new Data statement to your main

提交回复
热议问题