why the content of my pointer is nill?

hi,
I create a pointer, but the content of this pointer is nill. why this happen?
==========================================
MobileNode* M;
==========================================
MobileNode is a class.
When you declare a pointer it is uninitialized. To create an object you need to do it with new.
Anyway in modern C++ you should not use raw pointers at all. If you have to use pointers use the modern smart pointers: https://mbevin.wordpress.com/2012/11/18/smart-pointers/

It's uninitialized. So it's value will be nil if it's global, otherwise the value is indeterminate.
I want to use the pointer as a function parameter, is it ok??
NodeLocation(MobileNode* M=New MobileNode)
{
a=M->x();
}
1
2
3
4
NodeLocation(MobileNode* M=New MobileNode)
{
a=M->x();
} 

This is a memory leak. It's not ok.
a function that takes a pointer should just take it:

void NodeLocation(MobileNode* M)
{
if(M)
a=M->x();
else //handle error or do nothing or whatever is expected here
}

is this what you are asking, or can you ask a better, more detailed question?

Multiple posts on same problem is "doubleposting" and that is not helpful. Other post: http://www.cplusplus.com/forum/general/238758/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
  MobileNode* fubar = nullptr; // explicitly initialized null pointer
  NodeLocation( fubar ); // Assume that the function can handle null pointer

  MobileNode bar;
  fubar = &bar; // fubar now points to an automatic object
  NodeLocation( fubar );

  fubar = new MobileNode; // fubar now points to dynamic object
  NodeLocation( fubar );

  delete fubar; // must deallocate the dynamic object explicitly
  // bar deallocates automatically at end of function
}
Last edited on
Topic archived. No new replies allowed.