Thread: Confused in Pointer to Pointer address

  1. #1
    Registered User
    Join Date
    Mar 2021
    Posts
    1

    Confused in Pointer to Pointer address

    Here's my code

    Code:
    #include <stdio.h>
    
    void main(void)
    {
        int num=10;
        int *numPtr1;
        int **numPtr2;
    
        numPtr1 = &num;
        numPtr2 = &numPtr1;
        printf("%d\n", num);
        printf("%d\n", *numPtr1);
        printf("%d\n", **numPtr2);
        printf("%p\n", &num);
        printf("%p\n", numPtr1);//here
        printf("%p", numPtr2);//and here
    }
    Why numPtr2's address is not the same with numPtr1?
    printf("%p\n", numPtr1) and printf("%p", numPtr2) needs to display the same output right??

    For example, let num's address 0x7fffaca780b4. Then when I run this code, the output is

    **Output**
    10
    10
    10
    0x7fffaca780b4
    0x7fffaca780b4
    0x7fffaca780b8 <---????

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Sarith_peiris
    Why numPtr2's address is not the same with numPtr1?
    They are different pointers. numPtr1 points to num and numPtr2 points to numPtr1, i.e., the value of numPtr1 is the address of num and the value of numPtr2 is the address of numPtr1. So, what you should do is:
    Code:
    printf("%p\n", *numPtr2);
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. comparing the address of a pointer to an array address for size
    By ridgerunnersjw in forum C Programming
    Replies: 4
    Last Post: 04-17-2020, 06:25 PM
  2. Replies: 1
    Last Post: 08-24-2015, 07:43 AM
  3. getting confused with pointer to a pointer - 2d array
    By help_seed in forum C++ Programming
    Replies: 0
    Last Post: 12-02-2009, 09:48 PM
  4. pointer and smart pointer address
    By l2u in forum C++ Programming
    Replies: 14
    Last Post: 12-26-2006, 05:00 PM
  5. Should i pass address of pointer or just pointer???
    By howhy in forum C++ Programming
    Replies: 11
    Last Post: 09-02-2005, 04:05 AM

Tags for this Thread