Dereferencing a Pointer

suggest change
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 undefined behavior. p1 does not point to an int object just because its integer representation was set to 0xbad. The conversion itself is undefined if the result is not correctly aligned. p2 cannot be dereferenced because it is a null pointer. Hardware registers are sometimes accessed through implementation-defined addresses, but that is outside portable C and still requires an address the implementation defines as valid.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents