Thread: Pointer Assignment

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    10

    Pointer Assignment

    Hey guys, I have a question as to whether or not I am assigning the following correctly.

    The question states:
    Assume the declaration



    Code:
    int m = 35, *intPtr;
    double x, *dblPtr;


    a) Assign intPtr a value so it points to m
    b) Assign dblPtr a value so it points to x, amd then use the pointer to assign x the value of 5.3

    On (a), I think it is:
    Code:
    intPtr = &m;
    On (b), I think it is:

    Code:
    dblPtr = &x;
    *dblPtr = 5.3;
    I am questioning myself as to whether I should have used the * operator in assigning the first statements (for instance, *intPtr = &m and *dblPtr = 5.3)

    I think I am right on the first set. Can someone please let me know? Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What you have now is correct. Still, you could change it to what you were considering, compile, and observe what you get.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Your code looks right as is.

    Look at the two statements for dblPtr. One assigns an address, the other assigns a value. The pointer itself holds an address, which is why you assign directly to dblPtr. But the value should be assigned to the dereferenced pointer, which is why you added the * for the second one.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Replies: 3
    Last Post: 06-19-2004, 10:24 AM
  5. assignment makes pointer from integer
    By crescen7 in forum C Programming
    Replies: 4
    Last Post: 06-25-2002, 10:08 PM