0

What is the difference when I have for example,

int var1, *ptr;
ptr = &var1; // the pointer ptr copies the address of var1, hence ptr points to var1?

int var1, *ptr;
ptr = var1; // ptr points to var1, but does not have the address of var1, so can not change the value of address var1? 

int *var1, *ptr;
*ptr = *var1; // copy value of var1 into the location pointed to by ptr?

are my comments correct ?

Vazen
  • 9
  • 3
  • 2
    `int var1, *ptr; ptr = var1;` is ill-formed. The compiler should complain. – M.M Apr 21 '16 at 23:03
  • 2
    `*ptr = *var1;` is also ill-formed: `var1` cannot have `*` applied to it – M.M Apr 21 '16 at 23:04
  • 1
    The difference is that only the first is well formed. The other two will not compile. Your comment for the first example would be better as something like "the value of ptr is assigned the address of var1, hence ptr points at var1". The comments for the second and third examples are both incorrect, and can be replaced with "The assignment is invalid". – Peter Apr 21 '16 at 23:08

2 Answers2

0

The second (ptr = var1) and third (*ptr = *var1) options are wrong.

In the second case, you are asking for ptr to point to an address that is written in var1. I.e. var1 integer value will be interpreted as an address. Probably not what you want, and will cause compiler error or warning.

In the third case you are trying to dereference something that is not a pointer (*var1). Definitely a compiler error.

quarterdome
  • 1,559
  • 2
  • 12
  • 15
0
int var1, *ptr;
ptr = &var1; 

Take the address of the int variable var1, and assign that address to the variable ptr

int var1, *ptr;
ptr = var1; 

Assign the value of var1 to ptr. This requires a cast.

int *var1, *ptr;
*ptr = *var1; 

Assign the value pointed to by var1 to the value pointed to by ptr. (Note that as written, they both uninitialized pointers point to non-deterministic locations, which if they exist, hold undetermined values.)

James Adkison
  • 9,412
  • 2
  • 29
  • 43
tpdi
  • 34,554
  • 11
  • 80
  • 120