I wanted to know if there are alternative ways of assigning a pointer the address of the value its pointing to. For example, there's the usual way:
int a = 10;
int *ptr;
ptr = &a;
but at some places I see it declared like:
int *ptr = &a;
Are both of these ways equivalent? I am slightly confused because I always considered *ptr as giving the value of a, and not the address. Could anyone please explain? Thanks.
I am slightly confused because I always considered
*ptr
as giving the value ofa
, and not the address.
It is indeed a bit confusing as *
is used to declare a pointer, and also used as the dereference operator. The actual meaning of *
depends on the context - whether is used in a declaration, an initialisation or an assignment.
It's worth knowing the differences between 1) declaration, 2) initialisation, and 3) assignment.
int *ptr; // 1) this is declaration without initialisation.
int *ptr = &a; // 2) this is declaration **and** initialisation (initialise ptr to the address of variable a)
int b = 10;
*ptr = b; // 3) this is assignment, assign what pointed by ptr to value of variable b.
*
means that ptr
is a pointer to int
(but it has not pointed to any valid location yet).*
means that ptr
is a pointer to int
, and its initial value is the address of variable a
.*
is the dereference operator, ie assigning what pointed by ptr
to the value of variable b
.int *ptr; ptr = &a;
is to int *ptr = &a;
as int n; n = 3;
is to int n = 3;
.
That is, pointer declaration and initialisation is no different to normal variables. I prefer to use one line whenever possible since then there is less danger of having uninitialised variables.
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