What the *?
August 16, 2009 4:09 PM
Subscribe
int *ptr=(int*)2; ...could someone explain the use of the second asterisk?
So I'm trying to wrap my head around 'C' (...or is that 'C' around my head?)
I've been reading a pointer tutorial. I understand that I can declare a pointer by saying:
int *skybird;
...or declare it and assign an address of a variable to it by saying:
int *skybird=&dropkick;
...but if I declare the pointer and then assign the address to it in seperate statements, like thus:
int *skybird;
*skybird=&dropkick;
...Xcode warns me that my assignment makes integer from pointer without a cast. I take this to mean that the address of dropkick has no predetermined cast. So, I fix this by saying:
...
*skybird=(int)&dropkick;
...although this:
int *skybird=&dropkick;
...without having to using the integer operator on &dropkick, is fine. (I'm not sure why that is.)
I could declare a pointer and assign it a value right there and then, like:
int *crystal_palace=2;
...but I get the same cast warning as before. So I change it to:
int *crystal_palace=(int)2;
Makes sense to me. But, same warning. So I do as I've seen in my text books and type in an extra asterisk:
int *crystal_palace=(int*)2;
...and all is well. Thing is, I don't understand why. In short. Why the *?
This works:
int *skybird;
*skybird=(int)&dropkick;
But this doesn't:
int *skybird=(int)&dropkick;
My brain is casserole.
I've scoured my books but cannot find an explanation for the asterisk in the rvalue cast operator. (Am I speaking the correct jargon?) I understand the asterisk used before the pointer when declaring the pointer tells the compiler that I'm declaring a pointer. I understand that the asterisk is used before the pointer name when referencing the value stored at the location pointed to. I understand the no operator is used when the address pointed to needs to be referenced. I also understand that to reference the address of the pointer itself, the ampersand operator is used. I've looked and looked and looked, and I'm stuck. Bonus points if you could tell me why (int)*bo=(int*)2; is wrong.
posted by run"monty to computers & internet (21 comments total)
8 users marked this as a favorite
int *skybird;
*skybird=&dropkick;
Drop the first asterisk from your 2nd line — skybird is already of type pointer-to-int, so you're just wanting to set its value (i.e. what it points to) to &dropkick, the address of dropkick.
posted by BaxterG4 at 4:13 PM on August 16