#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    1
    Rep Power
    0

    Int value to double pointer


    Hello,
    I was wondering if i can assign an integer to double pointer in one statement without any temporary variable. Just curious if this is possible in C.

    int a = 10;
    int **p = ? ; //here how can i assign the value of 'a' to 'p'?

    Below works but i'm looking for a single statement (without temporary variable 'p').
    int a =10;
    int *p = &a;
    int **p1 = &p;

    Thanks in advance,
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,643
    Rep Power
    4248
    No. Think about what you're declaring for a moment:
    int **p;
    This declares a pointer-to-a-pointer-to-an-int variable.

    Now if you have an integer:
    int a = 10;

    You cannot assign a pointer-to-a-pointer-to-int type variable to the address of a, without another variable in between.
    int *p1 = &a; // This assigns the address of a to a pointer to int.

    In the above statement, we now have a pointer-to-int being pointed to an int. Now, we can do this:
    p = &p1; // Now this works because we are pointing to a pointer-to-int.

    Make sense?

    By the way, you'd better not make p1 a temporary variable, if you want to access a from p. The variable p1 should have a lifetime at least as long as a and p, otherwise undefined mojo could happen.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo

IMN logo majestic logo threadwatch logo seochat tools logo