Pointer and assignment question

N

needin4mation

Hi, in this statement:

int num1, *ptr;
num1=50;
ptr=&num1;
*ptr = (*ptr+25);


The indirection operator in (*ptr+25) says take the value that is held
in the address pointed to *ptr (which is the address of num1 the value
being 50).

So what does the *ptr on the left side of the assignment do? Is it
saying take the result of the right side (75) and assign it to the
location in memory pointed to by *ptr (or &num1)?
 
V

Victor Bazarov

Hi, in this statement:

int num1, *ptr;
num1=50;
ptr=&num1;
*ptr = (*ptr+25);


The indirection operator in (*ptr+25) says take the value that is held
in the address pointed to *ptr (which is the address of num1 the value
being 50).

So what does the *ptr on the left side of the assignment do? Is it
saying take the result of the right side (75) and assign it to the
location in memory pointed to by *ptr (or &num1)?

Yes. 'num1' should after that have the value 75.

V
 
K

Karl Heinz Buchegger

Hi, in this statement:

int num1, *ptr;
num1=50;
ptr=&num1;
*ptr = (*ptr+25);

The indirection operator in (*ptr+25) says take the value that is held
in the address pointed to *ptr (which is the address of num1 the value
being 50).

So what does the *ptr on the left side of the assignment do? Is it
saying take the result of the right side (75) and assign it to the
location in memory pointed to by *ptr (or &num1)?

Yes. The * is necessary, because on the left side you always implicitely
specify the address of where to store the right hand side

You dont write:

int i;
&i = 5;

meaning: store 5 at *the address of* i

you write
i = 5;

and the compiler knows that it has to take the address of the target
in contrast to j = i; where it has to take the value of i.

Consequently you also write

*ptr = ....

(ptr already holds an address, * gives you the corresponding object)
if you want to store something at the memory location where ptr points to.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top