|
The de-reference operator *:
|
Example:
int a, b, *p; // p can store a reference to an int typed variables |
The de-reference operator *:
|
Example:
int a, b, *p; // p can store a reference to an int typed variables p = &a; // p contains the referenceto variable a |
The de-reference operator *:
|
Example:
int a, b, *p; // p can store a reference to an int typed variables p = &a; // p contains the reference to variable a *p = *p + 1; // is equivalent to: a = a + 1; // because *p returns the variable a when p = &a |
The de-reference operator *:
|
Example:
int a, b, *p; // p can store a reference to an int typed variables p = &a; // p contains the reference to variable a *p = *p + 1; // is equivalent to: a = a + 1; // because *p returns the variable a when p = &a p = &b; // Now: p contains the reference to variable b |
The de-reference operator *:
|
Example:
int a, b, *p; // p can store a reference to an int typed variables p = &a; // p contains the reference to variable a *p = *p + 1; // is equivalent to: a = a + 1; // because *p returns the variable a when p = &a p = &b; // Now: p contains the reference to variable b *p = *p + 1; // is equivalent to: b = b + 1; // because *p returns the variable b when p = &b |
Example:
#include <stdio.h>
int main(int argc, char *argv[])
{
int a = 4, b = 8, *p;
p = &a; // Now *p is an alias for a
*p = *p + 100; // ≡ a = a + 100
printf("a = %d, b = %d\n", a, b);
p = &b; // Now *p is an alias for b
*p = *p + 200; // ≡ b = b + 200
printf("a = %d, b = %d\n", a, b);
}
|
Key: after the assignment p = &x;, the expression *p is an alias for x
DEMO: demo/C/set2/deref-op2.c
The * operator is the inverse operator for the & operator
This identity is valid for any variable x:
*(&x) ≡ x // Their data types are same too !
|
Example:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
i = 4;
printf("i = %d\n", i );
*(&i) = 9999; // Equiv to: i = 9999;
printf("i = %d\n", i );
}
|
DEMO: demo/C/set2/ref-var0.c
|
The precedence of the operators will help you understand how the expression is evaluated.