Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning an address to a pointer

Tags:

c++

c

pointers

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.

like image 209
QPTR Avatar asked Jan 07 '16 11:01

QPTR


2 Answers

I am slightly confused because I always considered *ptr as giving the value of a, 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.
  • In 1) the * means that ptr is a pointer to int (but it has not pointed to any valid location yet).
  • In 2) the * means that ptr is a pointer to int, and its initial value is the address of variable a.
  • In 3) the * is the dereference operator, ie assigning what pointed by ptr to the value of variable b.
like image 107
artm Avatar answered Oct 19 '22 04:10

artm


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.

like image 37
Bathsheba Avatar answered Oct 19 '22 04:10

Bathsheba