Docsity

Understanding Pointers: Why, Declaration, Assignment, Access, and Uses, Slides of Computer Engineering and Programming

Partial preview of the text

Download Understanding Pointers: Why, Declaration, Assignment, Access, and Uses and more Slides Computer Engineering and Programming in PDF only on Docsity!

Introduction to Pointers

Overview

1. Why Pointer Variables?

2. Boxes Again

3. What is a Pointer Variable?

4. Declaring a Pointer Variable

5. Assignment to Pointers

6. Accessing a Pointer

7. Two Uses of *

8. More Examples

9. Coding Call by Reference

  1. Boxes Again

The box occurs at memory address 1232

(say):

int x; x

x

3. What is a Pointer Variable?

 A pointer variable can

contain the memory address

of another variable.

  1. Assignment to Pointers

 The operator for returning the address of a

variable is &

int x = 5; int *countptr; countptr = &x;

Assigment in Pictures int x = 5; x

1232 (say)

int *countptr; countptr

countptr = &x; countptr

x

countptr

Usually, drawn as:

Initialising a Pointer

int *xptr;

float *yptr; xptr = NULL; yptr = NULL;

  1. Accessing a Pointer int c = 13; int *countptr; countptr = &c; printf("The value of countptr is %lu\n", countptr);

Result:

  1. Two Uses of * int *countptr;

means countptr can point to an integer variable

All other occurrences of * mean dereference:

printf("...", *countptr);

  1. More Examples

a gptr

a gptr

a gptr

int a = 3; *gptr; gptr = &a; *gptr = 7;

The & and * Operators Fig. 7. #include <stdio.h> int main() { int a = 7 ; int aptr; aptr = &a; / continued on next slide */

printf("Address of a is %lu\n", &a); printf("Value of aptr is %lu\n\n", aptr); printf("Value of a is %d\n", a); printf("Value of aptr is %d\n\n", aptr); printf("%s\n", "Proving that * and & are complements of each other."); printf("&aptr = %lu\n", &aptr); printf("*&aptr = %lu\n", *&aptr); return 0; }

Declarations and Initialisations int i = 3, j = 5, *p = &i, *q = &j, *r; double x; Expression Equivalent Expression Value p == &i p == (&i) 1 (true) p = i + 7 p = (i + 7) illegal **&p *p (^3) r = &x r = (&x) illegal

  1. Coding Call by Reference

9.1. Call by Value Reminder

9.2. Call by Reference Version

9.3. Swapping