June 21st, 2013, 04:06 PM
Int value to double pointer
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,
June 21st, 2013, 04:16 PM
No. Think about what you're declaring for a moment:
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.
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