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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

To prevent a pointer from pointing to an unknown, undefined memory address, it<br />

should be assigned an address immediately, or if the address is not yet known, the<br />

value 0 or NULL. When a pointer is assigned the value 0 or NULL, it is called a null<br />

pointer. This prevents a valid memory address from being determined by chance when<br />

the pointer is used, thus causing errors that are difficult to find.<br />

int *ptr1 = NULL;<br />

int *ptr2 = 0;<br />

// NULL pointer<br />

// NULL pointer<br />

To keep track when dealing with pointers, you should always use a meaningful name<br />

for a pointer.<br />

int *ptr_var = &var;<br />

As in this example, _var has been appended to the name of the pointer to make it clear<br />

that this pointer points to the address of var. You can also assign an address to a<br />

pointer after it has been declared.<br />

int *ptr_var; // undefined pointer<br />

…<br />

ptr_var = &var; // defined pointer - ptr_var points to var<br />

1.3.1 Direct Address Assignment<br />

A pointer can also be assigned a direct address in memory during initialization. <strong>The</strong><br />

following example shows a direct address assignment:<br />

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

#include <br />

int main()<br />

{<br />

int *ptr = (int *)0x0061ff14; // typecast to an int* - ptr points to 0x0061ff14<br />

printf("ptr points to: %p\n", ptr);<br />

}<br />

return 0;<br />

ptr points to: 0061ff14<br />

To assign a desired address to a pointer, a number (the desired address) must first be<br />

typed into a pointer, in this case an int pointer. This tells the compiler that it is a pointer<br />

to the constant address 0x0061ff14.<br />

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

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

Saved successfully!

Ooh no, something went wrong!