Thread: Use addresses of dynamically declared objects?

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912

    Use addresses of dynamically declared objects?

    I'm told I should initialize pointers to the address of the item.
    i.e. char *mypoin = &someotherchar;

    I've never seen the &operator used in examples of dynamiccally allocated objects. Do I need to put it there? If I don't, is it automatically set to the address?

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    >>char *mypoin = &someotherchar;

    If someotherchar exists on the stack, you use the & operand to get the memory address of the variable and then initialise it to the pointer as above

    If someotherchar was itself a pointer to a variable, then you would not use the & operand, you would just "char *mypoin = someotherchar;" This would set mypoin to point to the same memory address as someotherchar

    Code:
    int x = 10,	  
    *ptrx = &x, //note use of '&'
    *ptrFS = ptrx; // '&' not used
    
    cout << *ptrFS;
    This outputs 10 which was the origonal value of x

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    194

    Re: Use addresses of dynamically declared objects?

    Originally posted by Sean
    I'm told I should initialize pointers to the address of the item.
    i.e. char *mypoin = &someotherchar;

    I've never seen the &operator used in examples of dynamiccally allocated objects. Do I need to put it there? If I don't, is it automatically set to the address?
    When an object is dynamically created using new or alloc a pointer is returned. Since it is a pointer, you do not need the & to get the address of the actual data, the return pointer is the address of the actual data.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Global objects and exceptions
    By drrngrvy in forum C++ Programming
    Replies: 1
    Last Post: 09-29-2006, 07:37 AM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  3. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 09:45 PM
  4. viewing declared struct objects using gdb
    By Lynux-Penguin in forum Linux Programming
    Replies: 1
    Last Post: 07-20-2003, 06:46 PM
  5. Dynamic list of Objects in External File
    By TechWins in forum C++ Programming
    Replies: 3
    Last Post: 12-18-2002, 02:05 PM