CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #2
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,164

    Re: What is this statement doing?

    Code:
    int *myPtr = new int;
    The right hand side of the above line dynamically allocates a single integer on the heap returns a pointer of type int*. The left hand side of the above line implicitly copy constructs a pointer on the stack using the pointer returned from the new expression. It is the equivalent of writing:

    Code:
    int *myPtr(new int);
    The result is that myPtr now points to a dynamically allocated piece of memory. Incidently, this needs to be released using delete when you have finished with it else you will have a memory leak.
    Code:
    delete myPtr;
    The above line deletes the allocation that myPtr points to, any attempt to access the address myPtr currently still points to will yeild undefined behaviour.

    Now you might see the problem with the code you posted...
    Quote Originally Posted by g.eckert View Post
    I previously tried something similar to this and the app kept crashing
    Code:
    int *myPtr;
    
    cout....
    cin>> *( myPtr );  //Store input into the value myPtr points to
    The problem is that you have constructed an integer pointer myPtr but the pointer has not been initialised or assigned to point to a valid piece of memory. In effect, the pointer could be pointing anywhere. What you need to do is point it to a piece of memory that holds a valid integer. You can do this dynamically, or you can allocate a stack integer variable as follows.

    Code:
    int var = 0;
    int *myPtr = &var; //now myPtr points somewhere valid.
    
    //You can use myPtr from now on to access var
    This aside, why on earth do you want to purposely use pointers to access everything? If you cannot access a single object directly, then the next best thing is accessing it by reference, but if that is not possible (through design constraints), then only as a last resort should you access by pointer. They should NOT be used when there is no need.
    Last edited by PredicateNormative; April 17th, 2009 at 06:13 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured