Domanda

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?

È stato utile?

Soluzione 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.

Altri suggerimenti

The code you posted doesn't include a declaration of x_ptr, but for the code to be valid, the type of x_ptr must be int**: a pointer to a pointer to an integer.

The expression *x_ptr means the thing that x_ptr points to. Since x_ptr is a pointer to a pointer to an integer, *x_ptr is a pointer to an integer.

Since x is an integer variable, &x is the address of that variable. So what the assignment is doing is taking the address of the variable x and storing it into the place in memory that x_ptr points to.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top