Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in C: why is the * needed in *address_of_x = &x when getting the address of x?

Tags:

c

syntax

pointers

Suppose we have the following code, which takes x, stores the value 4 in it, then stores the address of x in a pointer variable:

int x = 4;
int *address_of_x = &x;

What is the purpose of the * in int *address_of_x? I understand * to be used for dereferencing a pointer - it takes an address and tells you what's stored there. But if an address is being stored, then what are we dereferencing? Or are we not dereferencing anything at all? Why isn't it written as:

int address_of_x = &x;
like image 662
Data Avatar asked Jan 19 '26 15:01

Data


2 Answers

* in int *address_of_x = &x; is not de-referencing @Eugene Sh.
It is part of the type declaration: pointer to int.

int x = 4;
int *address_of_x = &x;

same as

int x = 4;          // declare x as int
int *address_of_x;  // declare address_of_x as pointer to int
address_of_x = &x;  // Assign the address of x to address_of_x

Why isn't it written as: int address_of_x = &x;

&x is not an int. &x is an int *, a pointer (or address). A pointer is not an integer.

like image 183
chux - Reinstate Monica Avatar answered Jan 22 '26 10:01

chux - Reinstate Monica


In an expression, the * is the dereference operator. In a declaration (which you have here), it's part of the syntax of a pointer declarator. You're declaring address_of_x to be a pointer to int rather than just an int.

The idea that was behind this syntax is that declarations and usage of identifiers should look similar (you typically use a pointer by dereferencing it) for convenience.

Also note that the * is needed for every identifier declared as a pointer, even if you declare multiple identifiers in a single declaration, like this:

int *a, *b;

If you write

int *a, b;

instead, b would not be a pointer. In general, it's best practice to avoid declaring more than one identifier per declaration, though.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!