After the pointer has been declared and initialized, when did you prefix the literal variable with an asterisk, and when not?

Does a simple literal point to an address and * a literal point to the actual value at the address? So AFTER:

int i = 0; int *iPointer = &i; 

The following expression will look for the memory address VALUE AT & i:

 *iPointer 

and the following will just give the memory address & i:

 iPointer 

I took a step and confirmed my hypothesis, but I want to make sure (you never know with these things).

I assume that I'm just confused by the * character for different purposes in declaring and accessing.

+6
source share
2 answers

Yes, this is absolutely correct.

Also note that & can also declare a link depending on context.

In a declaration , * declares a pointer type.

When applied to a pointer (for example, *ptr ), it represents the dereference operator and returns the value that the pointer points to.

Note that operator * can be overloaded, so you can also apply it to objects, not just pointers, and do what you need.

+8
source

Uses the use of imitations.

If you have a pointer p that points to an integer value, you access that integer value by dereferencing p using the unary operator * , as in

 x = *p; 

The type of the expression *p is int , so the declaration of p is

 int *p; 

The variable type p is "pointer to int " or int * . However, the declaration is written so that the expression type *p is int .

So, anytime you want to access the integer value pointed to by p , you must use *p . If all you need is the address value contained in p , you just use p . For example, dereferencing a NULL pointer results in undefined behavior, so at least you want to check that the value of the pointer is not NULL before trying to dereference it:

 if (p != NULL) x = *p; 

In the condition, we are dealing with the value contained in p , so we are not looking for it. In the statement, we are dealing with the value of p , so we are looking for it there.

Please note that the ad

 int* p, q; 

coincides with

 int *p; int q; 

in that only p declared as a pointer; q declared as a regular int .

+2
source

Source: https://habr.com/ru/post/922755/


All Articles