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 output below code. However, when I delete line getline(cin, desc); pointer data never was NULL. Why does it happens? What should I do to allocate memory in function with string got form getline()?
#include <cstdio>
#include <iostream>
using namespace std;
struct Data
{
string desc;
int number;
};
void function1(int number, string desc, Data *data)
{
data = new Data;
data -> desc = desc;
data -> number = number;
printf("DURING: %p\n", data);
}
int main(int argc, char const *argv[])
{
int number;
string desc = "TEXT TEXT";
getline(cin, desc);
scanf("%i",&number);
Data *data;
printf("BEFORE: %p\n", data);
function1(number,desc,data);
printf("AFTER: %p\n", data);
return 0;
}
OUTPUT:
BEFORE: 0x0
DURING: 0x7f9ab25008c0
AFTER: 0x0
However if i delete line: getline(cin, desc); OUTPUT:
BEFORE: 0x103de4068
DURING: 0x7f8ed2c04aa0
AFTER: 0x103de4068
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 inmain
.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:
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:...then in
main
, you'll just define an instance of the object:You define a pointer and don't assign anything to it:
By definition
*data
can point to anything "it wants". So, theBEFORE
andAFTER
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 forDURING
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 yourmain