int a = 1;
int *a_pointer = &a;
To dereference a_pointer
and change the value of a, we use the following operation
*a_pointer = 2;
This can be verified using the following print statements.
printf("%d\n", a); /* Prints 2 */
printf("%d\n", *a_pointer); /* Also prints 2 */
However, one would be mistaken to dereference a NULL
or otherwise invalid pointer. This
int *p1, *p2;
p1 = (int *) 0xbad;
p2 = NULL;
*p1 = 42;
*p2 = *p1 + 1;
is usually undefined behavior. p1
may not be dereferenced because it points to an address 0xbad
which may not be a valid address. Who knows what's there? It might be operating system memory, or another program's memory. The only time code like this is used, is in embedded development, which stores particular information at hard-coded addresses. p2
cannot be dereferenced because it is NULL
, which is invalid.