Comment by codegeek
4 days ago
"Are pointers really that hard for so many people to understand?"
The * vs & always gets me and not to mention if I ever have to deal with Pointer Math.
4 days ago
"Are pointers really that hard for so many people to understand?"
The * vs & always gets me and not to mention if I ever have to deal with Pointer Math.
Think of it as types. All of the following are the same thing (declare p as an int* type). It's important for the end :
Now remember that the type is a memory address. I'm sure it is semantically wrong for whatever reason somebody will explain but it helps to think about it. So you can do :
Both sides of the "=" are the same type (int* is an address, and &my_number is also an address, the one of my_number).
Now p is a pointer (or an int* or an address), and *p is... an int ! So this is totally valid :
and for anything else than int you need to malloc that so you will see a lot of :
which makes sense because malloc returns an address (the beginning address of the content of s ; yet again somebody will tell me I'm wrong to call it "the content of s" so sorry for that).
> int* p
I don't like that syntax, because it confuses people. It might be sensible to think of the type as (int *), but C just doesn't work this way. You might never declare more that a single variable in a statement, but it still gives people the wrong intuition.
> int* p
I very much prefer that syntax, because the '*' is part of the type, not part of the variable name.
> You might never declare more that a single variable in a statement
Yes, you can do that, and in fact if you want to declare multiple pointers on the same line, you are required to put a '*' in front of every pointer variable name.
Personally, I've always considered this to be a defect of the language. Would it really be so awful to have to write instead:
But of course that's not the language we have.
I'd be very curious to know the motivation for requiring a '*' in front of each pointer variable name, as opposed to once with the type. So far the only ones I've thought of (not mutually exclusive) are:
a) we REALLY love terseness, and
b) ooh look at this clever hack I came up with for variable declaration syntax.
2 replies →
*pointer = what pointer points to &thing = address of thing