Use addresses of dynamically declared objects?

This is a discussion on Use addresses of dynamically declared objects? within the C++ Programming forums, part of the General Programming Boards category; I'm told I should initialize pointers to the address of the item. i.e. char *mypoin = &someotherchar; I've never seen ...

  1. #1
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913

    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,789
    >>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, 08:37 AM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 11: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, 07: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21