Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

Does the plain literal refer to the address and *literal refer to the actual value at the address? So, AFTER:

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

the following expression will lookup the VALUE AT memory address &i:

*iPointer

and the following will simply yield the memory address &i:

iPointer

I stepped through and verified my hypothesis, but I want to make sure (you never know with these things).

I guess I'm just confused by the * symbol's different purposes in declaration and access.

like image 797
Wuschelbeutel Kartoffelhuhn Avatar asked Aug 13 '12 17:08

Wuschelbeutel Kartoffelhuhn


People also ask

Where do you put an asterisk for pointers?

When declaring a pointer type, place the asterisk next to the type name. Although you generally should not declare multiple variables on a single line, if you do, the asterisk has to be included with each variable.

What does * After a variable mean in C?

Here, * is called dereference operator. This defines a pointer; a variable which stores the address of another variable is called a pointer. Pointers are said to point to the variable whose address they store.

When a pointer variable is declared an _ must be placed in front of the variable name?

Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double ) too.

How many asterisk are valid before declaring a pointer variable?

Simply remembering to put one asterisk per pointer is enough for most pointer users interested in declaring multiple pointers per statement.


1 Answers

Yes, that's absolutely correct.

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

In a declaration, * declares a pointer type.

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

Note that operator * can be overloaded, so you can also apply it to objects, not only pointers, and have it do whatever you want.

like image 190
Luchian Grigore Avatar answered Sep 22 '22 04:09

Luchian Grigore