How to Read or Write Data to a Pointer in C

Embedded C for microcontrollers



In this article, we go over how to read or write data to a pointer in C.

So a pointer is a reference to a memory address or memory location.

A memory location can store data.

How much data it can store depends on the bits of the microcontroller.

If the microcontroller is 16 bits, it can store data of 16 bits.

If the microcontroller is 32 bits, it can store data of 32 bits.

So a pointer references a memory location.

You can then read data from this memory location or write data to this memory location.

It's as simple as that.

So below we create a program in which we initialize a pointer variable and assign it a value, read the data from the pointer, write new data to the pointer, and then read it again.



The first thing that we do is we create a variable data of type char, which we set equal to 100.

We output the value of the data.

We then output the address of the data variable represented by, &data.

We then create a pointer. Remember a pointer is a memory address location. We set our pointer, pAddress, of type char to, &data. This gives it the memory address of the data variable.

To then read the data from this pointer, we create another variable, which will hold the data. We call this variable, value, of type char.

We then output the value of this variable.

To write data to this pointer, we reference the pointer through, *pAddress. We set the value equal to 70.

Now we output the data from data variable.

The output from this program is shown below.



So you can see how data was originally equal to 100.

The address of the variable data is 0x7ffdf8672ae6. Notice that every time you run this program, you may get different addresses generated.

We then show the contents stored in the pointer variable set equal to the memory location of the data variable.

We then write a new value to the pointer variable of 70.

Now when we show the value of the data variable, it has now changed to 70.

So this is how we can read from pointers or write new data to pointers using C.

HTML Comment Box is loading comments...