lecture 18 pointer 2

48
1 6.1 Addresses and Pointers Recall memory concepts from Ch2 1 = 00000001 7 = 00000111 ? = arbitrary 1’s and 0’s ???? 8 10 11 12 13 14 15 16 x1 x2 distanc e address name Memory - content int x1=1, x2=7; double distance; int *p; int q=8; p = &q; p q 16

Upload: turjo987

Post on 11-Nov-2014

45 views

Category:

Engineering


4 download

DESCRIPTION

East West University Bangladesh , computer science teaching lectures, NB:only C lecturer in university who provides Digital lectures

TRANSCRIPT

Page 1: Lecture 18 pointer 2

1

6.1 Addresses and Pointers Recall memory concepts from Ch2

1 = 00000001

7 = 00000111? = arbitrary 1’s and 0’s

????

8

10

11

12

13

14

15

16

x1

x2

distance

addressname Memory - content

int x1=1, x2=7;

double distance;

int *p;

int q=8;

p = &q;p

q

16

Page 2: Lecture 18 pointer 2

* has different meanings in different contexts

a = x * y; multiplication int *ptr; declare a pointer * is also used as indirection or

de-referencing operator in C statements.

ptr = &y; a = x * *ptr;

2

Page 3: Lecture 18 pointer 2

3

Example: Pointers, address, indirection

int a, b;int *c, *d;a = 5;c = &a;d = &b;*d = 9;print c, *c, &cprint a, b

?

?

?

?

memory

10

11

12

13

14

a

b

c

addressname

c=11 *c=5 &c=13

a=5 b=9

5

11

d 12

9

Page 4: Lecture 18 pointer 2

4

Exercise: Trace the following code

int x, y;int *p1, *p2;x = 3 + 4;Y = x / 2 + 5;p1 = &y;p2 = &x;*p1 = x + *p2;*p2 = *p1 + y;print p1, *p1, &p1print x, &x, y, &y

?

?

?

?

memory

510

511

512

513

514

x

y

p1

addressname

p2

Page 5: Lecture 18 pointer 2

5

Exercise

Give a memory snapshot after each set of assignment statements

int a=1, b=2, *ptr;ptr = &b;a = *ptr;*ptr = 5;

a 102

b 104

ptr 106

Page 6: Lecture 18 pointer 2

6

NULL pointer

A pointer can be assigned or compared to the integer zero, or, equivalently, to the symbolic constant NULL, which is defined in <stdio.h>.

A pointer variable whose value is NULL is not pointing to anything that can be accessed

Page 7: Lecture 18 pointer 2

7

Pointer Initialization

iPtr

s

dPtr

int *iPtr=0;char *s=0;double *dPtr=NULL;!!! When we assign a value to a pointer during it is declaration, we mean to put that value into pointer variable (no indirection)!!! int *iPtr=0; is same as

int *iPtr;iPtr=0; /* not like *iPtr = 0;

*/

Page 8: Lecture 18 pointer 2

8

Many-to-One PointingA pointer can point to only one location at a time, but several pointers can point to the same location.

/* Declare and initialize variables. */int x=-5, y = 8;int *ptr1, *ptr2;

/* Assign both pointers to point to x. */ptr1 = &x;ptr2 = ptr1;

The memory snapshot after these statements are executed

x 444 -5

y 446 8

Ptr1 448 444

ptr2 450 444

Page 9: Lecture 18 pointer 2

9

Exercise

int x=2, y=5, temp;int *ptr1, *ptr2, *ptr3;

// make ptr1 point to x ptr1 = &x;

// make ptr2 point to y ptr2 = &y;

Show the memory snapshot after the following operations

2

x

5

y

?

temp

ptr1 ptr2 ptr3

Page 10: Lecture 18 pointer 2

10

Exercise

// swap the contents of

// ptr1 and ptr2

ptr3 = ptr1;

ptr1 = ptr2;

ptr2 = ptr3;

Show the memory snapshot after the following operations

2

x

5

y

?

temp

ptr1 ptr2 ptr3

Page 11: Lecture 18 pointer 2

11

Exercise

// swap the values pointed

// by ptr1 and ptr2

temp = *ptr1;

*ptr1 = *ptr2;

*ptr2 = temp;

Show the memory snapshot after the following operations

5

x

2

y

5

temp

ptr1 ptr2 ptr3

Page 12: Lecture 18 pointer 2

12

Comparing Pointers

You may compare pointers using >,<,== etc. Common comparisons are:

check for null pointer if (p == NULL) … check if two pointers are pointing to the same location

� if (p == q) … Is this equivalent to � if (*p == *q) …

Then what is if (*p == *q) … compare two values pointed by p and q

Page 13: Lecture 18 pointer 2

13

Pointer types

Declaring a pointer creates a variable that is capable of holding an address

And addresses are integers! But, the type we specify in the

declaration of a pointer is the type of variable to which this pointer points

!!! a pointer defined to point to an integer variable cannot also point to a float/double variable even though both holds integer address values !!!

Page 14: Lecture 18 pointer 2

Example: pointers with different types

int a=5;double b=23.452;int *iPtr;double *dPtr;iPtr = &a;dPtr = &b;

the variable iPtr is declared to point to an int the variable dPtr is declared to point to a double

14

5

23.453

102

106

a 102

b 106

iPtr 114

dPtr 118

122

Page 15: Lecture 18 pointer 2

15

6.4 Pointers in Function References (!IMPORTANT!) In C, function references are call-by-value except

when an array name is used as an argument. An array name is the address of the first element Values in an array can be modified by statements

within a function To modify a function argument, a pointer to the

argument must be passed scanf(“%f”, &X); This statement specifies that the

value read is to be stored at the address of X The actual parameter that corresponds to a

pointer argument must be an address or pointer.

Page 16: Lecture 18 pointer 2

16

Call by Value

void swap(int a,int b){ int temp;

temp = a; a = b; b = temp; return;}

main()

{

int x = 2, y = 3;

printf("%d %d\n“,x,y);

swap(x,y); printf("%d %d\n“,x,y);

}

Changes made in function swap are lost when the function execution is over

Page 17: Lecture 18 pointer 2

17

Call by referencevoid swap2(int *aptr, int *bptr){ int temp;

temp = *aptr; *aptr = *bptr; *bptr = temp;

return;}

main()

{

int x = 2, y = 3;

printf("%d %d\n“,x,y);

swap2(&x, &y); printf("%d %d\n“,x,y);

}

Changes made in function swap are done on original x and y and. So they do not get lost when the function execution is over

Page 18: Lecture 18 pointer 2

18

Trace a programmain(){ int x0=5, x1=2, x2=3; int *p1=&x1, *p2;

p2 = &x2;

swap2(&x0, &x1);

swap2(p1, p2);

printf(“%d %d %d\n”, x0, x1, x2);

}void swap2(int *a, int *b){

int tmp; tmp = *a; *a = *b; *b = tmp; return;}

Name Addr Value

x0 1

x1 2

x2 3

p1 4

p2 5

6

a 7

b 8

tmp 9

Page 19: Lecture 18 pointer 2

19

Now we can get more than one value from a function

Write a function to compute the roots of quadratic equation ax^2+bx+c=0. How to return two roots?

void comproots(int a,int b,int c,

double *dptr1, double *dptr2)

{

*dptr1 = (-b - sqrt(b*b-4*a*c))/(2.0*a);

*dptr2 = (-b + sqrt(b*b-4*a*c))/(2.0*a);

return;

}

Page 20: Lecture 18 pointer 2

20

Exercise cont’dmain(){

int a,b,c;double root1,root2;

printf("Enter Coefficients:\n");scanf("%d %d %d",&a,&b,&c);

computeroots(a,b,c,&root1,&root2);

printf("First Root = %lf\n",root1);printf("Second Root = %lf\n",root2);

}

Page 21: Lecture 18 pointer 2

21

Trace a programmain(){ int x, y; max_min(4, 3, 5, &x, &y); printf(“ First: %d %d”, x, y); max_min(x, y, 2, &x, &y); printf(“Second: %d %d”, x, y);}void max_min(int a, int b, int c, int *max, int *min){ *max = a; *min = a; if (b > *max) *max = b; if (c > *max) *max = c; if (b < *min) *min = b; if (c < *min) *min = c; printf(“F: %d %d\n”, max, *max);}

name Addr Value

x 1

y 2

3

4

5

a 6

b 7

c 8

max 9

min 10

Page 22: Lecture 18 pointer 2

22

Pointer Arithmetic Four arithmetic operations are supported

+, -, ++, -- only integers may be used in these operations Arithmetic is performed relative to the variable type being

pointed to MOSTLY USED WITH ARRAYS (see next section)

Example: p++; if p is defined as int *p, p will be incremented by 4 (system

dependent) if p is defined as double *p, p will be incremented by 8(system

dependent when applied to pointers, ++ means increment pointer to point to

next value in memory

Page 23: Lecture 18 pointer 2

23

6.2 Pointers and Arrays The name of an array is the address of the first elements (i.e. a pointer to the

first element) The array name is a constant that always points to the first element of the

array and its value can not be changed. Array names and pointers may often be used interchangeably.Example

int num[4] = {1,2,3,4}, *p, q[];p = num;q = p; // or q = num;/* above assignment is the same as p = &num[0]; */printf(“%i”, *p); // print num[0]p++;printf(“%i”, *p); // print num[1]printf(“%i”, *q); // print num[0]printf(“%i”, *(p+2)); // print num[2]

Page 24: Lecture 18 pointer 2

24

Pointers and Arrays (cont’d) You can also index a pointer using array notation

char string[] = “This is a string”;

char *str;

int i;

str = string;

for(i =0; str[i]!=NULL; i++)

printf(“%c”, str[i]);

Page 25: Lecture 18 pointer 2

25

Two Dimensional ArraysA two-dimensional array is stored in sequential memory locations, in row order.

int s[2][3] = {{2,4,6}, {1,5,3}};

int *sptr = &s[0][0]; Memory allocation:

s[0][0] 2 s[0][1] 4s[0][2] 6s[1][0] 1s[1][1] 5s[1][2] 3

A pointer reference to s[0][1] would be *(sptr+1)A pointer reference to s[1][1] would be *(sptr+4)

row offset * number of columns + column offset

Page 26: Lecture 18 pointer 2

26

6.7 Dynamic Memory Allocation

Dynamically allocated memory is determined at runtime

A program may create as many or as few variables as required, offering greater flexibility

Dynamic allocation is often used to support data structures such as stacks, queues, linked lists and binary trees.

Dynamic memory is finite Dynamically allocated memory may be freed during

execution

Page 27: Lecture 18 pointer 2

27

Dynamic Memory Allocation

Memory is allocated using the: malloc function (memory allocation) calloc function (cleared memory allocation)

Memory is released using the: free function

The size of memory requested by malloc or calloc can be changed using the: realloc function

Page 28: Lecture 18 pointer 2

28

malloc and calloc•Both functions return a pointer to the newly allocated memory

•If memory can not be allocated, the value returned will be a NULL value

•The pointer returned by these functions is declared to be a void pointer

•A cast operator should be used with the returned pointer value to coerce it to the proper pointer type

Page 29: Lecture 18 pointer 2

29

Example of malloc and calloc

int n = 6, m = 4;double *x;int *p;

/* Allocate memory for 6 doubles. */x = (double *)malloc(n*sizeof(double));

/* Allocate memory for 4 integers. */p = (int *)calloc(m,sizeof(int));

X

p

Page 30: Lecture 18 pointer 2

&*%&@#*!int f (void) { int s = 1; int t = 1; int *ps = &s; int **pps = &ps; int *pt = &t;

**pps = 2; pt = ps; *pt = 3; t = s;}

s == 1, t == 1s == 2, t == 1

s == 3, t == 3s == 3, t == 1

Page 31: Lecture 18 pointer 2

Rvalues and Lvalues

What does = really mean?int f (void) { int s = 1; int t = 1; t = s; t = 2;}

left side of = is an “lvalue” it evaluates to a location (address)!right side of = is an “rvalue” it evaluates to a value

There is an implicit * when a variable isused as an rvalue!

Page 32: Lecture 18 pointer 2

Parameter Passing in C Actual parameters are rvalues

void swap (int a, int b) { int tmp = b; b = a; a = tmp;}

int main (void) { int i = 3; int j = 4; swap (i, j); … }

The value of i (3) is passed, not its location!swap does nothing

Page 33: Lecture 18 pointer 2

Parameter Passing in Cvoid swap (int *a, int *b) { int tmp = *b; *b = *a; *a = tmp;}

int main (void) { int i = 3; int j = 4; swap (&i, &j); … }

The value of &i is passed, which is the address of i

Is it possible to define swap in Python?

Page 34: Lecture 18 pointer 2

Beware!int *value (void){ int i = 3; return &i;}

void callme (void){ int x = 35;}

int main (void) { int *ip; ip = value (); printf (“*ip == %d\n", *ip); callme (); printf ("*ip == %d\n", *ip);}

*ip == 3*ip == 35

But it could really be anything!

Page 35: Lecture 18 pointer 2

Manipulating Addresseschar s[6];s[0] = ‘h’;s[1] = ‘e’;s[2]= ‘l’;s[3] = ‘l’;s[4] = ‘o’;s[5] = ‘\0’;printf (“s: %s\n”, s);

s: hello

expr1[expr2] in C is just syntactic sugar for*(expr1 + expr2)

Page 36: Lecture 18 pointer 2

Obfuscating Cchar s[6];*s = ‘h’;*(s + 1) = ‘e’;2[s] = ‘l’;3[s] = ‘l’;*(s + 4) = ‘o’;5[s] = ‘\0’;printf (“s: %s\n”, s);

s: hello

Page 37: Lecture 18 pointer 2

Fun with Pointer Arithmeticint match (char *s, char *t) { int count = 0; while (*s == *t) { count++; s++; t++; } return count;}

int main (void){ char s1[6] = "hello"; char s2[6] = "hohoh";

printf ("match: %d\n", match (s1, s2)); printf ("match: %d\n", match (s2, s2 + 2)); printf ("match: %d\n", match (&s2[1], &s2[3]));}

&s2[1] &(*(s2 + 1)) s2 + 1

match: 1match: 3match: 2

The \0 is invisible!

Page 38: Lecture 18 pointer 2

Condensing match

int match (char *s, char *t) { char *os = s; while (*s++ == *t++); return s – os - 1; }

int match (char *s, char *t) { int count = 0; while (*s == *t) { count++; s++; t++; } return count;}

s++ evaluates to spre, but changes the value of sHence, C++ has the same value as C, but has unpleasant side effects.

Page 39: Lecture 18 pointer 2

Quiz

What does s = s++; do?It is undefined!

If your C programming containsit, a correct interpretation of yourprogram could make s = spre + 1,s = 37, or blow up the computer.

Page 40: Lecture 18 pointer 2

Type Checking in C Java: only allow programs the

compiler can prove are type safe

C: trust the programmer. If she really wants to compare apples and oranges, let her.

Python: don’t trust the programmer or compiler – check everything at runtime.

Exception: run-time type errors for downcasts and array element stores.

Page 41: Lecture 18 pointer 2

Type Checkingint main (void) { char *s = (char *) 3; printf ("s: %s", s);}

Windows XP (SP 2)

Page 42: Lecture 18 pointer 2

Type Checkingint main (void) { char *s = (char *) 3; printf ("s: %s", s);}

Windows 2000

(earlier versions of Windows would just crash the whole machine)

Page 43: Lecture 18 pointer 2

43

Exercise

Study Section 6.3 from the textbook

Page 44: Lecture 18 pointer 2

44

Skip

Study section 6.5 from the textbook

We studied section 6.6 Strings under one dimensional char arrays in ch 5

Page 45: Lecture 18 pointer 2

45

6.7 Dynamic Memory Allocation

Dynamically allocated memory is determined at runtime

A program may create as many or as few variables as required, offering greater flexibility

Dynamic allocation is often used to support data structures such as stacks, queues, linked lists and binary trees.

Dynamic memory is finite Dynamically allocated memory may be freed during

execution

Page 46: Lecture 18 pointer 2

46

Dynamic Memory Allocation

Memory is allocated using the: malloc function (memory allocation) calloc function (cleared memory allocation)

Memory is released using the: free function

The size of memory requested by malloc or calloc can be changed using the: realloc function

Page 47: Lecture 18 pointer 2

47

malloc and calloc•Both functions return a pointer to the newly allocated memory

•If memory can not be allocated, the value returned will be a NULL value

•The pointer returned by these functions is declared to be a void pointer

•A cast operator should be used with the returned pointer value to coerce it to the proper pointer type

Page 48: Lecture 18 pointer 2

48

Example of malloc and calloc

int n = 6, m = 4;double *x;int *p;

/* Allocate memory for 6 doubles. */x = (double *)malloc(n*sizeof(double));

/* Allocate memory for 4 integers. */p = (int *)calloc(m,sizeof(int));

X

p