Just getting into C++. I'm getting constantly thrown off track when I see the symbol for multiply (*
) being used to denote the dereferencing of a variable
for example:
unsigned char * pixels = vidgrabber.getPixels();
Does this throw other people off? What's the tip for getting my head around this?
Thank you.
p.s. I have another reasonably simple question, that didn't get answered :( here: beginner question: add/subtract to value rather than just be that value pretty please! and thanks for your time!
I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
As illustrated, a variable (such as number ) directly references a value, whereas a pointer indirectly references a value through the memory address it stores. Referencing a value indirectly via a pointer is called indirection or dereferencing.
pointers are just like usual objects, they store a value inside, thus they refer to the stored values in them. "Dereferencing" is when we "disable" this connection to the usual value within and use the identifier of p to access/refer to a different value than the value stored in p .
C, and by inheritance C++, are swamped with operators and are inherently context-sensitive. You will have to get used to it:
If *
appears before the name of a variable that is being declared (or defined), it's a type modifier and makes that variable a pointer.
If it is a unary prefix operator for a variable that is part of an expression, it's dereferencing (or whatever it's been overloaded to).
If it is a binary infix operator for two variables that are part of an expression, it's multiplication (or whatever it's been overloaded to).
(From this you can see that the *
in your unsigned char * pixel
isn't a dereferencing unary prefix, but a type modifier.)
Note that &
pretty much resembles *
, only it's meaning is different: it makes a variable a reference, is the address-of operator, or the binary AND.
One recommendation when writing your own code is to "cuddle" the * when using as a pointer/deref:
unsigned char *pixels = ...
if (*pixels == ...)
and to space the * when using as a multiply:
int y = x * 7;
There are other clues you can use (such as the fact that pointer deref is a unary operator while multiple is a binary operator).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With