I am a beginner with the programming language C. I am working from example code online and am trying to analyze the following,
int x = 0, y = 16;
*x_ptr = &x
It's the second line that I want to make sure I'm understanding syntactically. I have only just encountered the concept of pointers and am trying to crack that nut conceptually. How then should I read the code on line 2?
A variable is a storage location.
A storage location stores a value.
A storage location is associated with a type.
A storage location of type T holds a value of type T.
A storage location is not a value.
Using a storage location to produce a value produces the value stored in the storage location.
Applying the &
operator to a storage location of type T produces a value. The type of the value is "pointer to type T".
Applying the *
operator to a value of type "pointer to type T" produces a storage location of type T.
From these facts you can deduce the meaning of your program fragment.
However, your program fragment as given is almost certainly a typo. You meant to say
int x = 0, *x_ptr = &x;
Let's write that out in a longer form to make it easier to read.
int x;
int *x_ptr;
x = 0;
x_ptr = &x;
x
and x_ptr
are storage locations. The first of type int, the second of type pointer to int.
The value zero is assigned to the location x
.
The &
operator is applied to storage location x
producing a value of type pointer to int.
That value is assigned to storage location x_ptr
.
If you then said
*x_ptr = 123;
then the *
takes the value stored in location x_ptr
and turns the pointer back into a storage location -- x
-- and then stores 123 into that storage location. x
is now 123
, not 0
.
Make sure you have this solid. This is the key to understanding all of C.