1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the...

67
1 Pointers
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    1

Transcript of 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the...

Page 1: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

1

Pointers

Page 2: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

2

Why Pointers• They provide the means by which

functions can modify arguments in the calling function.

• They support dynamic memory

allocation.

• They provide support for dynamic data structures, such as binary trees and linked lists.

Page 3: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

3

What Are Pointers• A pointer is the memory address of an

object.

• A pointer variable is a variable that is specifically declared to hold a pointer to an object of its specified type.

• This address is the location of another object (typically another variable) in memory.

Page 4: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

4

1003

Variable in memory

Memory address

100010011002100310041005

.

.

.

Page 5: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

5

Pointer Declaration

• General syntax:

type *name;

int *m; //The variable m can hold a

//pointer to type int.

char *ch;

int count, *y, q;

Page 6: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

6

Two Pointer Operators

Address Operator: &

Dereference Operator: *

Both & and * have a higher precedence than all other arithmetic operators except the unary minus, with which they share equal precedence.

Page 7: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

7

& Operator

• The & is a unary operator that returns the memory address of its operand.

& “the address of”

m = &count;

m receives the address of count.

m count

100

Page 8: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

8

* Operator

* is the complement of &. It is a unary operator that returns the value located at the address that follows.

* “at address”

q = *m;

q receives the value at address m. ?

Page 9: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

9

#include <stdio.h>int main(void){  int target, source=10;  int *m;  m = &source;  target = *m;   printf("%d", target);  

return 0;}

Put the value 10 into a variable called target.

Page 10: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

10

Pointer Assignments

• You can use a pointer variable on the right-hand side of an assignment statement to assign its value to another pointer.

• When both pointers are the same type, the situation is straightforward.

Page 11: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

11

#include <stdio.h>int main(void){  int x = 99;  int *p1, *p2;   p1 = &x;  p2 = p1;    printf("%p %p", p1, p2);   printf(''%d %d\n", *p1, *p2);     return 0;}

Page 12: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

12

Illustrates Distinction between a pointer var value & a Dereferenced var.

main( )

{ int i = 777, *p = &i;

printf (“value of i:%d\n”, *p);

printf (“Addr of i:%u or %p\n”, p, p);

}

Output Value of i: 777

Address of i: 234880259 or dfffcfc

u - (unsigned Dec integer)

p - (whatever way is Default for system) - Here is Hex.

Page 13: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

13

Example 1

int i = 1, *j, *k;

Assume addresses of i, j, k are respectively Byte addresses 10, 20, 30

i:10 j:20 k:30

1. j = &i;

int var Pointer var Pointer var

i:10 j:20 k:30

10 ?

?1 ?

1

Page 14: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

14

2. *j = 2;

i:10 j:20 k:30Stores 2 at the memory location pointed to by j.

3. i = *j + 1;

i:10 j:20 k:30

* has higher precedence than +. Assigns to i the contents of the location pointed to by j, incremented by 1.

10 ?

1 2 10 ?

12 3

Page 15: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

15

4. k = &i;

i:10 j:20 k:30

5. printf (“%d”, *k);

output: 3

103 10

Page 16: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

16

int a=42, b=53, *p1, *p2;p1 = &a;

p2 = p1;

p2 = &b;

p1? p2? *p1? *p2?

Example 2

Page 17: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

17

p1p2

?

?

int a=42, b=53, *p1, *p2;

p1 = &a;p1p2

?

42

p2 = p1;

p1p2

42

p1p2

42p2 = &b;

42

53

53

53

53

Page 18: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

18

int *p1, v1;v1 = 0;p1 = &v1;*p1 = 42;v1? p1? *p1?

int a=8, b=9; int *p1, *p2;p1 = &a;p2 = &b;p1 = p2; vs. *p1 = *p2;

Example 3

Page 19: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

19

p1

p2

8

9

before afterp1

p2

8

9

p1

p2

8

9

before afterp1

p2

9

9

p1 = p2;

*p1 = *p2;

Page 20: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

20

Example 4

# include <stdio.h>

main( )

{

int j, i, *intptr;

scanf(“%d%d”, &i, &,j);

intptr = i > j ? &i:&j;

printf(“%d\n”, *intptr);

}

Address of the larger var is stored in ? : then the larger number is output.

Page 21: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

21

Example 5int a=3,b=7,*p; p = &b;

a b p

*p=2**p–a;

printf (“b= %d\n”, b);

“The object pointed to by p (i.e., b) is assigned the value of 2**p–a.”

1) 2 * *p 2 * 72) 14 – 3 113) Which is assigned? b

3 7

11

Page 22: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

22

int i, *p = &i;correct

int *p = &i, i;sequence wrong.

The variable must be defined before

the address can be assigned.

Pointer Initialization

Page 23: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

23

p = &i; p “points to” i

p = 0; “Null” is usually defined as

0.

p = NULL; Pointer constant points “nowhere”.

p = (int *) 1307;cast to pointer to int.1307 is an absolute address in

memory.

Page 24: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

24

int i = 3, j = 5, *p = &i, *q = &j, *r;double x;

r ?

i:10 j p:50 q x

1) p = i + 7; The only integer value that can be assigned to a pointer variable directly is the special value 0 (NULL).

To assign any other value requires a cast (int *) (i + 7)

3 5

ILLEGAL

?

Page 25: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

25

2) **&pAll are unary operators. &p - The address of p (50).

*&p - “The Addr

stored at p” (10)

i:10 p:5

**&p – The contents of the address (*&p)

“The contents of the variable pointed to by p”

i.e., 3

3

1

2 10 3

Page 26: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

26

3) r = &x; Illegal Why?

x is a double variable

r is pointer to int.

4) 7 * *p / *q + 7 i:10 j

Dereference Right to Left p q1. *q 52. *p 33. 7 * 3 [21]4. 21/5 45 4 + 7 11

3 5

Page 27: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

27

5) *(r = &j) *= *p

4 2 1 5 3 j - int var

p - pointer to int

j i r - pointer to int

r p

1. &j - Address of j

2. r = r points to j

3. *p contents of thing

pointed to by p i.e., 3

4. *( ) Location pointed to by r, i.e., j.

5. *= *r *= *p; *r = *r * *p;

3

5

1

1

Page 28: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

28

int *v=(int *)100; Byte Address.

100 v102 v + 1104 v + 2106 v + 3108 v + 4

Pointer Arithmetic

assume int are 2 bytes long.

Page 29: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

29

char *ch=(char *)3000;int *i=(int *)3000;

30003001

30033002

30043005

chch+1ch+2ch+3ch+4ch+5

i

i+1

i+2

Pointer Arithmetic (cont.)

Page 30: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

30

Pointer Arithmetic (cont.)• Only two operations are allowed.

– Addition and subtraction.

e.g. p++; p--; p1=p1+12;

• Cannot multiply or divide pointers.

• Cannot add two pointers.

• Cannot add or subtract type float or double to or from pointers.

Page 31: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

31

Call by Reference

• Passing a ADDRESS of the argument to a formal parameter which is a POINTER of the same type as the argument.

• Code within the function can change the value of the argument passed to the function.

Page 32: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

32

Steps1) Declare a function parameter to be a

pointer.

2) Pass an address as an argument when the

function is called.

3) Use the dereferenced pointer in the

function body to reference the argument

in the calling function.

Page 33: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

33

#include <stdio.h>void swap(int *x, int *y);

int main (void){  int i=10, j=20;  

printf("i and j before swapping: %d %d\n", i, j);   swap(&i, &j); /* pass the addresses of i and j */  

printf("i and j after swapping: %d %d\n", i, j);  

return 0;}

Page 34: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

34

void swap(int *x, int *y)

{  int temp;  

temp=*x; /* save the value at address x */  *x =*y;    /* put y into x */  *y=temp;  /* put x into y */}

Page 35: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

35

Storage Classes

Page 36: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

36

Every variable or function in C has 2 attributes:

Type Storage Class

General form:

storage-specifier  type var_name

Storage Class : determines how the compiler allocates memory to that variable.

Auto Extern Register Static

Page 37: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

37

Storage Class of a C object defines its:

1) Spatial Territory- Defines where it can

be referred to in the program. Its Scope

or Visibility.

2) Temporal Authority- Defines when an

object is available. The Extent to which

it exists.

Page 38: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

38

Auto VariablesThe storage class auto can only be used in a block:

it cannot be used at the global level.

1) Spatial Limitation(scope): The auto variable is limited to the block in which it is

defined and its sub-blocks. LOCAL.

2) Temporal Limitation(extent): Are alive only when the block in which they are defined is running. Variable does not exist before block execution, when block terminates it dies(mortal).

Page 39: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

39

Impact of Auto• Auto is the default SC for local vars because it

makes the most efficient use of memory.

• Good programmers use Auto when ever possible because their lifetime is brief and their scope is limited to one function.

• They provide an effective way to isolate the actions of each program unit from the others.

Page 40: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

40

auto• Most common of the four storage classes.

• Variables declared within function bodies are auto by default.

• Thus auto is rarely explicitly specified.

auto int a,b,c;

auto float f;

Page 41: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

41

Unintentional interference between functions is minimized and, making it much easier to debug large programs.

Constant allocation and deallocation of auto vars does add some overhead to the the execution time, but since is done quite efficiently, the time wasted is minimal and the advantages of the added modularity are great.

Page 42: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

42

When a block is entered, the system allocates memory for the auto variables.

“LOCAL” i.e., Those declared in the block.

When Block is exited the variables are released and their values lost.

IF re-enter theBlock? _________

Memory is reallocated.

Page 43: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

43

Call by Reference with Auto Parameters

1) When the block is suspended, such as when it calls another function,the variable is suspended but can still be accessed and changed(e.g. actual argument in a func call).

2) It can still be referenced and changed through a pointer to it. When the block becomes active again, the variable becomes active i.e., can directly reference it by name.)

Page 44: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

44

Extern• Primary purpose is to make variables visible to

other compilation units.

• Must be defined in the global area of a program, that is outside of any block.

• All global variables( i.e., those defined outside any function) are EXTERN by default.

!!!!! EXTERN variables are DANGEROUS and should be used with CAUTION !!!!!

Page 45: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

45

Extern Characteristics

• Spatial Limitation(global): It is visible from its definition to the end of the program. It can be referred to and changed by all blocks that come after it as well as by other programs that are aware of its existence.

• Temporal Limitation(Immortal): The whole life of the program. From the time of its allocation till the end of the program.

Page 46: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

46

Variables declared outside of a function have

extern storage class by default.

i.e., even if don’t use keyword extern.

Extern Var’s are initialized to 0 automatically.

extern - “Look for the variable elsewhere –

either in this or another file.”

extern (cont.)

Page 47: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

47

• See 3 handouts on program examples

Relevant to EXTERN storage class.

K-5, K-6, K-7.

Page 48: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

48

Register Storage Class

Variables so declared should be stored in high speed memory i.e.,

Registers(cpu) provided if is possible to do so.

Defaults to Auto if register not available

Page 49: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

49

Typically, the compiler has only a few such registers available.

Many are required for system use & can’t be allocated otherwise:

* Base Addr of program

* Return Addr after pgm execution ends,

* Instruction reg, program counter,

etc……..

Page 50: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

50

It is an attempt to improve execution speed.Most frequently accessed variable – loop control

variable or function parameters.

register int i ;for (i = d, i <LIMIT, ++i){

… }

If storage class is present & Type is absent - get int.

register i ;

Page 51: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

51

RecommendationDon’t Use

• The standard states that you can’t compute the address of a register. That means you can’t use the address operator or indirection operator(*) with a “Register” variable.

• Secondly, the compiler may ignore your recommendation.

Page 52: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

52

Static Storage Class

A static variable can be defined inside a block(local) or in the global area of the program. Its characteristics differ slightly depending on where it is defined.

We will look at each separately.

Page 53: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

53

Local Static VariablesStatic variable is defined inside a block: 1. Spatial Limitation(scope): LOCAL,

undefined outside the block.2. Temporal Limitation(extent):

Immortal. It lives as if it were a global variable.

What are the consequences of the immortal extent?

Page 54: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

54

Locally defined Static variables are one of the truly significant features of the “C” language.

1) Allow a “Local variable” to retain its previous value when a block is re-entered.

(Not the case with Auto)

2) In other languages, these variables must be declared globally, which reduces the benefits of data hiding and isolation.

3) The variable will be automatically initialized to 0 when allocated.

Page 55: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

55

Void f(void)

{

static int cnt = 0;

++ cnt;

if (cnt % 2 == 0)

. . . . . .

else . . . . .

}

* 1st Time Function Invoked cnt is set to 0.

* Upon EXIT cnt NOT cleared from memory

* Next invocation ,retains previous value.

Page 56: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

56

Global Static Variables

Global variables-that is, variables defined outside the scope of all blocks-can be referred to by other compilation units.

To prevent a global variable from being exported to the LINKER for reference by other compilation units, it can be declared static.

Page 57: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

57

Global Static Characteristics:1) Spatial Limitation(scope): Global.

Visible from its definition to the end of the compile unit. Guarantees that the scope does not extend beyond its spatial area, i.e., the current complilation unit.

1) Temporal Limitation(extent) Immortal. Same as local static, it lives as global variables live.

Page 58: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

58

Static Extern Variable

Restricted in scope to the “remainder of the file” in which they are defined. Not known to other files(compilation units).

void f(void)

{

…… /* v not available here */

}

static int v;

void g(void)

}

…… /* v can be used here */

}

Page 59: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

59

A Function can be Static: The scope of the function is limited to this file only(privacy concern). Is known throughout the entire file.

void f(int a)

{

…….. /* g() is available here,

} but not in other files */

static int g(void)

{

……..

}

Page 60: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

60

Default Initialization

Extern & Static vars are initialized to 0 by the system.

Auto & Register are usually not initialized by system.

Start will garbage.

Page 61: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

61

Type Qualifiers• Two type qualifiers: const volatile

• They are used in declarations and must be coded after the storage class but precede the type names that they qualify.

static const int k = 3;

• Control how variables may be accessed or modified.

Page 62: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

62

const• Variables of type const may not be changed

by your program.

• The compiler is free to place variables of this type into read-only memory (ROM).

const int a=10;

const int a=7; int *p=&a; //wrong

const int a=7; const int *p=&a; //correct

Page 63: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

63

#include <stdio.h>void sp_to_dash(const char *str);

int main(void){  sp_to_dash("this is a test");   return 0;}

void sp_to_dash(const char *str){  while(*str) {    if(*str= = ' ') printf("%c", '-'); if(*str= =' ') *str= '-'; wrong    else printf("%c", *str);      str++;  }}

Page 64: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

64

Volatile• The modifier volatile tells the compiler

that a variable's value may be changed in some unspecified way by the hardware.

– For example, a global variable's address may

be passed to the operating system's clock routine and used to hold the system time.

– Programmers use Volatile objects in advanced systems programming(beyond our scope).

Page 65: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

65

Declaration vs. Definition

In General, a Declaration is a program element that provides a compiler with essential information or useful advice.

When you specify the type of a variable

or parameter you are said to declare

variable or parameter.

Page 66: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

66

A definition causes a compiler to set aside memory at compile time (every variable definition is a declaration) - not always the reverse.

e.g. when you introduce a variable outside of any function definition (global variable), you both declare and define the variable, because you have: a) informed the compiler about the

variable’s type.b) caused the compiler to set aside memory

for the variable at compile time.

Page 67: 1 Pointers. 2 Why Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation.

67

When you introduce a variable inside a function definition(local), you only declare that variable, because the compiler does not set aside memory for such variable at compile time [memory in stack frame].

Functions are both declared & defined

Because: a) must specify return type.

b) compiler sets aside memory for

functions at compile time.