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.

1.6 Pointer to Arrays<br />

A pointer always increments or decrements by the number of bytes of the data type<br />

to which it points. For a char this would be one byte, for a double it would be 4 or 8<br />

bytes depending on the system.<br />

To illustrate this, in the following example we create an int array and store four values<br />

in it. Instead of the "usual" access to the elements of the array, we now use a pointer<br />

to access the first element in the array, and then increment the pointer three times in<br />

the for loop. This moves the pointer to the next position in the array.<br />

/* example 133 – pointer to arrays */<br />

#include <br />

int main (void)<br />

{<br />

int ivar[] = {2, 8, 5, 9};<br />

int *iptr;<br />

iptr = ivar; // ivar is an array, therefore we need no address operator &<br />

for (int i = 0; i < 4; i++) {<br />

printf("Address of ivar[%d] = %p\n", i, iptr );<br />

printf("Value of ivar[%d] = %d\n", i, *iptr );<br />

}<br />

iptr ++; // move to the next position<br />

}<br />

return 0;<br />

Address of ivar[0] = 0060FEE8<br />

Value of ivar[0] = 2<br />

Address of ivar[1] = 0060FEEC<br />

Value of ivar[1] = 8<br />

Address of ivar[2] = 0060FEF0<br />

Value of ivar[2] = 5<br />

Address of ivar[3] = 0060FEF4<br />

Value of ivar[3] = 9<br />

As you can see, the array ivar[] was stored at address 0x0060FEE8. This is also the<br />

address of the first element with the content 2. <strong>The</strong> value of the pointer was then<br />

increased by 4 bytes. So the next address in the array for the 2nd element is<br />

0x0060FEEC, whose content is the value 8. This allows access to the individual<br />

elements of an array. It is noticeable here that the & operator for an address<br />

assignment is missing. This is because according to the ANSI-C standard, an array name<br />

represents a pointer to the 1st element of the array. Another notation would be e.g.<br />

ptr_a = &a[0]; <strong>The</strong> address of the 1st element of array a is also passed to the pointer<br />

ptr_a with this command.<br />

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

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

Saved successfully!

Ooh no, something went wrong!