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
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
You're passing your pointer by value, so the function gets a copy of the pointer from main
, and can only affect its own copy of the pointer, not the pointer that's in main
.
Therefore, both before and after calling the function the pointer is just an uninitialized value, so it's likely to vary unpredictably (and, technically, printing it out, or using its value in any other way, leads to undefined behavior).
Pass the pointer by reference to get the function to modify the original pointer:
void function1(int number, string desc, Data *&data)
{
data = new Data;
data -> desc = desc;
data -> number = number;
printf("DURING: %p\n", data);
}
Then, when you've got this straightened out, you probably want to quit using raw pointers (almost) completely. There are almost always better ways to do things. In this case, the code you currently have in function1
should probably be in a constructor:
struct Data {
string desc;
int number;
Data(string desc, int number) : desc(desc), number(number) {}
};
...then in main
, you'll just define an instance of the object:
int main() {
int n;
std::cin >> n;
Data d{"TEXT TEXT", n};
}