Hacker News new | past | comments | ask | show | jobs | submit login

But &a gives you "int * *", and then it's dereferenced three times. How?



The int** is not dereferenced three times.

The cast says "treat this int* as an array of int*, then the first dereference says "give me the first element of that array", which gets you back the original int*.


See, this would be a better, shorter, and more insightful explanation than that an article full of mechanical transformations performed by hand.

"We start with a pointer-to-int called "a", take pointer to it and name it "p" (it's a pointer-to-pointer-to-int, although we store it in a pointer-to-whatever variable), then cast it to some weird type, dereference it thrice and store 1 into the resulting target. Two questions remain: a) what is that weird type? b) we have two levels of indirection but three dereferences, how does it work? The answer to the first question is that weird type is "pointer-to-array-of-pointers-to-int", and it helps us to answer the second question: dereferencing a value of that type is a no-op in arithmetical sense (but has a type-casting effect)."


Unless I'm mistaken, this is almost, but not quite correct. (Firstly, what's being cast is `p` which is a `void-pointer`.) More importantly, the latter cast says to treat p as a `pointer to an array of int-pointers`, which means that the first dereference actually gives you the array. Expressions with an array type in most contexts (including this one) decay into pointers to their first elements – thus the second dereference gets you the first element of the array, an int-pointer, and the third one gets you the integer being pointed to.

Also, because this array type is incomplete (it has no size), I don't think you could use it in any context where it didn't "decay" into a pointer to its first element (you can test what your compiler says if you try to measure the array's size with the sizeof operator when only using one dereference).


There is an array cast [] in there. So dereferencing that using a plain * takes you back to the original double pointer.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: