26.09.2023 Views

The C Programming Language - Pointers

This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher

This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>The</strong> address of var is now displayed on the far left. <strong>The</strong> content of var is represented<br />

as a hexadecimal value in the first 4 bytes, with the first byte on the right at position<br />

1. <strong>The</strong> decimal number 1234567 corresponds to the hexadecimal number 0x0012d687,<br />

which is stored at address 0x61ff1c in this example.<br />

In the next example, we declare a pointer variable of type int named ptr and assign it<br />

the address var. In the next line of code, we use the dereference operator * to access<br />

the variable pointed to by ptr, and store its contents in x. We then output the<br />

corresponding values.<br />

/* example 126 – pointers */<br />

#include <br />

int main()<br />

{<br />

int var = 1234567, x;<br />

int *ptr; // ptr is an int pointer<br />

ptr = &var;<br />

x = *ptr;<br />

// ptr = address of var<br />

// x = value of element pointed to by ptr<br />

printf("<strong>The</strong> value of x = %d\n", x); // x holds the value of var<br />

printf("<strong>The</strong> address of var = %p\n", ptr);<br />

printf("<strong>The</strong> address of x = %p\n", &x);<br />

printf("<strong>The</strong> address of ptr = %p", &ptr);<br />

}<br />

return 0;<br />

<strong>The</strong> value of x = 1234567<br />

<strong>The</strong> address of var = 0061ff1c<br />

<strong>The</strong> address of x = 0061ff18<br />

<strong>The</strong> address of ptr = 0061ff14<br />

<strong>The</strong> pointer variable ptr itself must of course also have a place in memory and was<br />

created here at address 0x0061ff14.<br />

<strong>The</strong> C <strong>Programming</strong> <strong>Language</strong> by Heimo Gaicher – Chapter <strong>Pointers</strong> 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!