lecture 9: pointers - university of california, san...

53
ECE15: Introduction to Computer Programming Using the C Language Lecture 9 : Pointers A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad

Upload: others

Post on 24-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

ECE15: Introduction to Computer Programming Using

the C Language

Lecture 9: Pointers

A. Orlitsky and A. Vardy, based in part on slides by S. Arzi, G. Ruckenstein, E. Avior, S. Asmir, and M. Elad

Page 2: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

❖ Need for something new ‣Three shortcomings of call by value

❖ Pointers ‣ The address & and indirection * operators ‣ Pointers and functions: call by reference ‣ Changing function parameters ‣ Returning multiple values ‣ Pointers and arrays ‣ Array arguments

❖ String arrays ‣String functions ‣ Command-line arguments ‣ File input and output

❖ Dynamic Memory allocationLecture 8 ECE15: Introduction to Computer Programming Using the C Language 2

Outline

Perhaps hardest

Page 3: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

?? 434 3

Problem Changing Parameters

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 3

x y?

x y43

temp

3

What to do?

Recall: Function arguments are passed by value

When we write f(x) to call a function f(int y), value of x copied into y f has no access to x

void swap(int x, int y) { int temp = x;

x = y;

y = temp; }

int main(void) { int x = 3, y = 4;

swap(x,y); }

Example: A function that swaps the values of x and y

Passing variables by value

Unchanged!

Saw

Page 4: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Problem Returning Multiple Values

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 4

Example: A function computing the roots

of a quadratic equation ax2 + bx + c = 0

What to do?

#include <stdio.h>

double quad_solve(int a, int b, int c){ double root[2]; ... root[0] = ... ; root[1] = ... ;

return root; }

int main() { double a = 1.0, b = 4.0, c = 1.0; double x[2]; x = quad_solve(a,b,c); printf("Roots: %d and %d\n", x[0],x[1]); return 0; }

#include <stdio.h>

double quad_solve(int a, int b, int c){ double root[2]; ... root[0] = ... ; root[1] = ... ;

return root[0], root[1]; }

int main() { double a = 1.0, b = 4.0, c = 1.0; double x[2]; x = quad_solve(a,b,c); printf("Roots: %d and %d\n", x[0],x[1]); return 0; }

Page 5: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

double average(int b[], int N) { int i, sum = 0; for (i = 0; i < N; i++) sum += b[i]; return sum / (double) N; }

int main() {

int a[1000000] = {1,2,...};

double avg = average(a,1000000); }

Problem with Arrays

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 5

Will the program copy the 1,000,000 integers

from a[] to b[]?

Example: Write a function calculating the average of an array of integers

What to do?

Page 6: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Summary and Unified Solution

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

❖ Shortcomings of call by value ‣ Functions cannot change the variables passed to them ‣ Functions cannot return multiple values ‣ Passing arrays to functions wastes memory and time

6

Instead of passing variable values

One idea solves all problems

Pass by value Pass by reference

Pass their addresses!

Page 7: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

❖ Need for something new ‣Three shortcomings of call by value

❖ Pointers ‣ The address & and indirection * operators ‣ Pointers and functions: call by reference ‣ Changing function parameters ‣ Returning multiple values ‣ Pointers and arrays ‣ Array arguments

❖ String arrays ‣String functions ‣ Command-line arguments ‣ File input and output

❖ Dynamic Memory allocationLecture 8 ECE15: Introduction to Computer Programming Using the C Language 7

Outline

Page 8: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

... ...1001 1002 10071003 100610051004 101110091000 1008 1010

x d c

Memory Allocation Reminder

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 8

{ double x; short d; char c; ... }

Every variable has an address in memory, which can be used to access it!

Memory organized as sequence of bytes Variables allocated prescribed number of bytes according to type Local variables allocated consecutive locations in variable stack

Example:

1000

1008

1010

Page 9: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

‣ In example: &x is 1000, &d is 1008, and &c is 1010 ‣ Works only for variables: &7 is a compilation error

Address and Dereference

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 9

Address operator: &a is the address of variable a

Dereference (indirection) operator: *a is the variable at address a, or pointed to by a

‣ In example: *(1000) is x and *(1008) is d

Variables holding addresses are called pointers

...

...

1001

1002

1007

1003

1006

1005

1004

1011

1009

1000

1008

1010

xd

c

1000

1008

1010

Page 10: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 10

ap

get addressp = &a

follow addressa = *p

Address & and indirection * are dual operations: &a is address of a while *p is variable at address p &*p is p and *&a is a

If pointer p points to variable a then *p is a and p is &a

Variables holding the address of (pointing to) some variable (or file, or function)

Page 11: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

For every type: int, double, char, boolean,...

There is a type pointing to it: pointer to int, pointer to double, ...

Declaration & Assignment

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 11

Declaration: type *pint *p; char *cp; double *pdbl; boolean *bp;

Remember by: *p (variable p points to) is an integer

Non-pointer types (e.g. int), can be assigned by us: int x = 5;

int *p = &x;int *p; p = &x;

Assignment: p = &a

For pointers, we don’t know address, hence ask program to initialize, via &

Or *p is an int, and the value of p (not of *p) is the address of x

Page 12: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Examples

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 12

char c, *p1=&c; double *p2, *p3, x; p2 = &x;

#include <stdio.h> int main() {

int a=1; int *pa; // pa points to int pa=&a; printf("*pa=%d\n", *pa);

int b=2, *pb; pb=&b; printf("*pb=%d\n", *pb);

int c=3, *pc=&c; printf("*pc=%d\n", *pc); }

declarations.cDeclaration + assignment

Pointers to other types

3-lines

2-lines

1-lineSlightly unintuitive convention allows

for 1-line declaration and assignment of

multiple variables and pointers

Declare before reference int *p4=&i, i;✘

Page 13: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Mechanics

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 13

1000 a3

Memory

q?

p?

. . .

. . .

Example 1:1000

1000

int a = 3; int *p,*q;

p = &a; q = p;

1000 a30

Memory

y?

p?

. . .

. . .

Example 2:

1000

30

int a = 30; int y; int *p;

p = &a; y = *p; *p = 42;

42

Page 14: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

❖ Local pointers not auto initialized. If pointer p not initialized then

puts nonsense in x and can crash program

❖ Recall unintuitive syntax when initializing with declaration:

Interpret: p is a pointer and its value (not *p’s value!) is &x

Advantage: declare and assign multiple variables and pointers in one line

❖ A single pointer can also be declared as

❖ Different pointer types cannot be mixed

❖ Several levels of indirection are possible **p ↔ *(*p), ***p, ****p, etc.

Details

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 14

int *p; double a; p = &a; û

But can be cast

p = (int*) &a;

*p = x x = *p

int *p = &x;

int* p; int* p, q;

Integer pointer now points to double.

Still risky, more later.

just int

Page 15: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Address Printing

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 15

#include <stdio.h>

int main() { double a=3.14159, *pa=&a;

printf("Address in hex: %p\n", pa);

long unsigned int addy = (long) pa;

printf("Address in decimal: %lu\n", addy); printf("Value is: %f\n", *(double*)addy);

return 0; }

print_pointer.c

❖ In rare occasions where need to print actual address, can use %p

❖ Prints address in hexadecimal

Page 16: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Precedence

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 16

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

Example

Expression Equivalent Expression Value

p == &*p p == &(*p) 1

**&p *(*(&p)) 3

r = &x r = &x Error

7**p/*q+7 (7*(*p))/(*q) + 7 11

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

*&p is simply pbinary and unary operators

What happens:

Page 17: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointers Resolve Shortcomings

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 17

Three shortcomings of call by value

Modifying calling parameters

Show how all resolved by pointers

Returning multiple values

Arrays

Page 18: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Modifying Function Parameters

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 18

void swap(int *px, int *py) {

int temp = *px;

*px = *py;

*py = temp; }

int main() {

int x = 5, y = 7;

swap(&x, &y);

...

?

?

?

py

px

temp

7

5

y

x1000

1004

1000

1004

5

5

7

. . .

. . .

Example: A function swapping the values of x and y

Functions can now change arguments!

To change function arguments: call with their addresses

Page 19: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

int main() {

int a; int *p = &a;

scanf("%d", &a); scanf("%d", p); }

scanf()updates contents of memory locations, hence called with their address &

scanf Mystery Resolved

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 19

Hey, why no &?

void swap(int *px, int *py) {

int temp = *px;

*px = *py; *py = temp; }

int main() {

int a, b; swap(&a, &b);

int *p = &a, *q = &b; swap(p, q); }

Q: Must we always call with & ?

swap.c

Page 20: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Returning Two Values

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 20

Task: Given a and b representing the numerator and denominator of a fraction a/b, reduce fraction to its lowest terms --- namely cancel all common factors of a and b..

void reduce(int *px, int *py);

ab

=75

100ab

=34

Example:

int a,b; ... reduce(&a,&b);

CallDeclaration

Call gcd(a,b)to compute the greatest common divisor of a and b, then divide both a and b by this common factor. Algorithm:

Implementation Need to return two values!

Page 21: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

#include <stdio.h> int gcd(int, int); void reduce(int *pnum, int *pden) { int d = gcd(*pnum,*pden);

if (d > 1){ *pnum /= d; *pden /= d; } }

Implementation

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 21

reduce.c

int main() { int num, den; printf("Numerator + denominator: "); scanf("%d %d", &num, &den); reduce(&num, &den); printf("Reduced: %d/%d\n", num, den); return 0; }

int gcd(int m, int n) {

int tmp;

while(n != 0){ tmp = n; n = m % n; m = tmp; } return m; }

Functions can now return two values!

Page 22: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Example: Adding Two Fractions

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 22

Task: Given two fractions a1 / b1 and a2 / b2 , represented by their numerators and denominators, compute and reduce their sum a/b.

ab

=5·5 + 2·4

60=

3360

=1120

a1b1

=5

12a2b2

=2

15

Example:

Implementation:

Algorithm: b -- least common multiple of b1 and b2 a = a1 (b /b1) + a2 (b /b2) Reduce the resulting fraction

void add(int *pa, int *pb, int a1, int b1, int a2, int b2);

lcm(12,15)

reduce(a,b)

int a, b, a1, b1; ... add(&a,&b,a1,b1,2,15);

CallDeclaration

Page 23: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

int gcd(int, int); void reduce(int *, int *);

int lcm(int m, int n) { // least common multiple return m*n/gcd(m,n); }

void add(int *pa, int *pb, int a1, int b1, int a2, int b2) { *pb = lcm(b1,b2); *pa = a1*(*pb/b1) + a2*(*pb/b2); reduce(pa,pb); }

Implementation

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 23

lcm(m,n) =m n

gcd(m,n)

add.c

int main(){ int a1, a2, b1, b2, a, b; printf("a1 b1 a2 b2: "); scanf("%d %d %d %d", &a1,&b1,&a2,&b2); add(&a,&b,a1,b1,a2,b2); printf("%d/%d + %d/%d = %d/%d\n",a1,b1,a2,b2,a,b); return 0; }

Pointers already

Page 24: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointers and Integers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 24

Every pointer holds a memory address, namely an integer Some, but not all, arithmetic operations allowed

≠+Pointer variables cannot be added, multiplied, or divided

3 arithmetic operations allowed on pointers:

Add a constant integer: p + 3 Subtract a constant: p - 3 Subtract pointers: p - q

Useful for handling arrays

type *p, *q;

p, q must point to same type

Page 25: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointer Arithmetic

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 25

char a[] = {'p','o','i','n','t','e','r'}; char *p = &a[3]; printf("%c%c%c!!\n", *(p+1),*(p-2),*(p-3));

int b[] = {3, 2, 4, 5, 1}; int *q = &b[3]; printf("%d %d %d!!\n",*(q+1),*(q-2),*(q-3));

Example:top!!

"pointer";

Similarly: p++, p--, ++p, --p, p-42, p += 2, q = p-2*(++a)

+/- constant: If p points to a type (int, double, char,..) of size sizeof(type)= n, then +/- 1 changes p by n bytes

Subtracting pointers of the same type yields # elements of that type between them in memory

123!!

int c[] = {3, 2, 4, 5, 1}; printf("%ld\n", &c[3]-&c[1]);2

pointer_math.c

Page 26: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointer Arithmetic Expressions

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 26

Expression Valuep + 1 304

(char*)p + 2 302

p++ 300

q – p 24

(char*)q -(char*)p 96

q - (char*)p Errorprintf("%p", p) 0x130

Example: Assuming an int occupies 4 bytes:

Values of following expressions?

int *p, *q;

p = (int*)300; q = (int*)400;

p is now 304

not an expression

Page 27: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Arrays as Pointers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 27

The basic use of an array is referencing its elements double salaries[800]; salaries[3]=-1000.; printf(“%d\n”, salaries[7]);

How is it implemented?

salaries[0], ..., salaries[799] are all variables of type doubleBut what is salaries itself?

salaries is just a pointer to salaries[0]

Array references implemented as:

*(salaries+i)salaries[i]

Array name is same as a pointer to its first element!

salaries+i&salaries[i]

*(salaries+2) *salaries

salaries[2] salaries[0]

salaries+2 salaries

&salaries[2] &salaries[0]

Page 28: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Array References via Pointers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 28

xx[yy] *(xx + yy)

Examples

char *p = array1; for (i=0; i<7; i++) printf("%c", p[i]);

0123456

int array2[] = {0,1,2,3,4,5,6}; int *q = &array2[3];

for (i=-3; i<4; i++) printf("%d", *(q+i));

char a[] = "pointer"; printf("%c%c%c = %d", 4[a],1[a],0[a],7[a]);top = 0

What?

pointer

char array1[] = "pointer";

int i;

for (i=0; i<7; i++) printf("%c", array1[i]);pointer

for (i=0; i<7; i++) printf("%c", *(array1+i));pointer

arr_ptr.c

Page 29: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

*salaries = 3.5; x = salaries[42];

*p = 3.5; x = p[42];

Therefore:

Arrays and Pointers: Differences

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 29

double salaries[800]; double *p;

Arrays act as pointers to their first element Are arrays and pointers the same?

Pointers are more flexible than arrays

Memory allocated for 800 variables of type doubleMemory allocated for one variable of type double*

ü ✘

Arrays do more than pointers

Arrays are "constant" pointers. Always point

to same address!int a[800], b[800]; int *p = a, *q = b;

p++; p = b; p = q;

üa++; a = b;✘

Page 30: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Arrays as Function Arguments

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 30

Function call with array argument passes array name: a pointer to array’s first element

void double_array(int ar_name[], int num_elts) { for (int i=0; i<num_elts; i++) ar_name[i]*=2; }

void print_array(int *array, int num) { for (int i=0; i<num; i++) printf("%d ", *(array+i)); printf("\n"); }

int main() { int ar[]={1,2,3,4,5}; double_array(ar, 5); print_array(ar, 5); return 0; }

Hence length must be passed separately

A string is an array of characters word is a pointer (to word[0]). Already address, no need for &

arr_arg1.c

Q: char word[10]; scanf("%s", word);

Why no &?

A:

EQUIVALENT

Page 31: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Arrays in Function Declaration

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 31

void fun(int a[]); void fun(int *a);equivalent

As we saw:

void fun(int []); void fun(int *);

void print_array(int [], int); void double_array(int *, int); int main() { int ar[]={1,2,3,4,5}; double_array(ar, 5); print_array(ar, 5); return 0; }

When only declaring function, can omit name

equivalent

void print_array(int *array, int num) { for (int i=0; i<num; i++) printf("%d ", array[i])); printf("\n"); }

void double_array(int arr[], int num) { for (int i=0; i<num; i++) *(arr+i)*=2; }

arr_arg2.c

Page 32: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

1 0 2 3 9 7

2-d Arrays as Pointers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 32

Collection of 2 horizontal arrays, each of size 3int ar[2][3]={{1,0,2},{3,9,7}}; 1 0 2

3 9 7

Initialization

ar[i]

ar[i][j], *(ar[i]+j)

i’th array (pointer to its first element)

Addressing

int ar[][3]={{1,0,2},{3,9,7}};

ar+i

(*(ar+i))[j], *(*(ar+i)+j)

pointer to i’th array

1-dimensional array of size 6int ar[][3]={1,0,2,3,9,7};Initialization

3 necessary

Addressing

Crazy C stuff Don’t worry!

(*ar)[3*i+j], *(*ar+3*i+j)

*ar pointer to first element

2dRef.c

Page 33: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

❖ Need for something new ‣Three shortcomings of call by value

❖ Pointers ‣ The address & and indirection * operators ‣ Pointers and functions: call by reference ‣ Changing function parameters ‣ Returning multiple values ‣ Pointers and arrays ‣ Array arguments

❖ String arrays ‣String functions ‣ Command-line arguments ‣ File input and output

❖ Dynamic Memory allocationLecture 8 ECE15: Introduction to Computer Programming Using the C Language 33

Outline

Page 34: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

String Arrays and Pointers

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Alternative declarations

34

// As arrays:

char class1[]="ece15"; // array

char class5[] = {'e','c','e','1','5','\0 '};

// As pointers:

char *class2 ="ece15"; // pointer char* class3 ="ece" "15"; // concatenation char* class4; class4="ece15"; // why?

...

string_def.c

char *pword;

scanf("%s", pword);✘

Page 35: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Useful String Functions

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 35

char *strcat(char *, char *);

int atoi(char *);

int sscanf(char *string, char *format, arg1,..);

int sprintf(char *string, char *format, arg1,..);

String length

Concatenate 1st, 2nd, returns location

Convert to int

Read from string

Write to string

<string.h>

int strlen(char *); string_fun.c

actually, size_t, used for object sizes, can treat as integer

int strcmp(char *, char *); 1st string <, =, or > than 2nd

char *strcpy(char *, char *); Copies 2nd to 1st, returns destination

<stdio.h> and <stdlib.h>

double atof(char *); to double

Page 36: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointer Arrays

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Arrays of int, double, char, ....

36

#include <stdio.h>

int main() {

char *stringArray[]={"First string", "Second string", "Third string"}; int i;

for (i=0; i<3; i++) printf("%s\n", stringArray[i]);

return 0; }

everything

Many applications

One next

pointers?How about array of...

Declaration (mnemonic)

ar[0], ar[1],.. point to integers

Array of int’s a[i] - int int a[];

Pointer to double *p - double double *p;

Array of pointers to int *a[i] - int int *a[];

double *a[];

char *a[];

string_array.c

Page 37: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Command-Line Arguments

If run frequently, skip prompt

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 37

> gcc c2f.c > a.out Celsius: 100 Fahrenheit: 212

Convenient way to run frequent commands

Task: Convert Celsius to Fahrenheit

> gcc c2f2.c

> a.out 100 Fahrenheit: 212

> gcc -o c2f.out c2f.c

Provide the program command-line argumentsAlmost all Unix commands use command-line arguments

> gcc c2f.c > ls *.c

Page 38: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Command-Line Arguments - Ctd

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

C provides the program two values Integer containing # stings in command line (incl. filename) - typically argc Array of pointers, each pointing to one of the strings - typically argv

38

> a.out Hello 1 world

argc: 4 argv[0]="a.out" argv[1]="Hello" argv[2]="1" argv[3]="world"

What if all values integers, wanted to increment all?

#include <stdio.h>

int main(int argc, char *argv[]) {

int i;

printf("%d arguments\n", argc-1);

for (i=1; i<argc; i++) printf("%s\n", argv[i]);

return 0; }

print_arguments.c

printf("%d\n", atoi(argv[i])+1);

increment.c

Page 39: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

#include <stdio.h>

int main() {

double cel;

printf("Celsius: "); scanf("%lf", &cel); printf("Fahrenheit: %.1lf\n", cel*1.8+32);

return 0; } #include <stdio.h>

int main(int argc, char *argv[]) {

int cel = atoi(argv[1]);

printf("Fahrenheit: %.1lf\n", cel*1.8+32);

return 0; }

Formula:

Celsius to Fahrenheit Conversion

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 39

F = 1.8 C + 32

Command line argumentsBefore

After

c2f2.c

c2f1.c

Page 40: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

The NULL Pointer

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 40

❖ Memory addresses are not of type int. Nevertheless, every pointer variable can take one special integer value: constant 0

❖ For clarity, when dealing with pointers, it is common to use NULL instead of 0. The constant NULL is defined in <stdio.h> as 0

int *p = (int *)100;

*p = 42; /* What will happen? */

0 is never a valid address

Setting pointer to NULL is a safe way to indicate it doesn’t point anywhere

int i, *p = NULL; .... p = &i;

if (p!=NULL) *p = 42;

null_pointer2.c

if (!p) *p = 42;

null_pointer1.c

Page 41: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

File Input / Output

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 41

fscanf(pin, "%d", &x);

FILE *pin = fopen("inputName", "r");

FILE *pout1 = fopen("outputName1", "w");

FILE *pout2 = fopen("outputName2", "a");

fclose(pin); fclose(pout1); fclose(pout2);

fprintf(pout1, "%d\n", x); fprintf(pout2, "%d\n", 2*x);

read

write

append

(over)Open

Read

Write

Close

String because more options: "r+", "w+", "wb", etc.

(after end )

Erases everything

previously there

Page 42: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Example

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Read values from input file, write squares in output file

42

#include <stdio.h> int main() { int x; FILE *input = fopen("inputFileName", "r");

FILE *output = fopen("outputFileName", "w");

while (fscanf(input, "%d", &x) == 1) fprintf(output, "%d\n", x*x);

fclose(input); fclose(output); return 0;

square_file.c

FILE *input if ( (input = fopen("inputFileName", "r") ) == NULL ) { printf("Couldn’t open inputFileName\n"); return 1;

} ... all okay... continue normal execution

fopen fails if "r" file doesn’t exist, no space for "w" file, etc. Returns NULL pointer, hence can check

0

Page 43: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Overwrite File

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Double all values in a file, writing new values in same file

43

#include <stdio.h> #define MAX_NUM 100 int main() { int ar[MAX_NUM], i=0, j; FILE *fp = fopen("FileName", "r");

while (fscanf(fp, "%d", &ar[i]) == 1) i++; fclose(fp);

fp = fopen("FileName", "w"); for (j=0; j<i; j++) fprintf(fp, "%d\n", 2*ar[i]);

fclose(fp);

return 0; }

No size bound? Temporary file or dynamic memory allocation

Double pay!!!

overwrite.c

Need to store values Use array

What if want to write at end of file?

open with “a”append.c

Page 44: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

❖ Need for something new ‣Three shortcomings of call by value

❖ Pointers ‣ The address & and indirection * operators ‣ Pointers and functions: call by reference ‣ Changing function parameters ‣ Returning multiple values ‣ Pointers and arrays ‣ Array arguments

❖ String arrays ‣String functions ‣ Command-line arguments ‣ File input and output

❖ Dynamic Memory allocationLecture 8 ECE15: Introduction to Computer Programming Using the C Language 44

Outline

Page 45: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointers to Void

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 45

What's a pointer to void?

Seen pointers to int, char, double, ….

Page 46: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Pointers to Type void

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 46

What if you need a pointer whose type is known only at run-time?

Use pointer of type void, then cast it at run-time

Generic: do not to variable of specific type (int, char, etc.)

Can assign address

Cannot reference, do pointer arithmetic, etc. (don’t know # bytes to use)

To reference need to first cast, so point to a specific type

Pointers of void

int a,b, *p1;

void *p2 = &b;

p1 = &a; b = *p1 + *(int*)p2;

double a=5., b, *p1=&a; void *p2

p2 = p1; b = *p1 + *(double*)p2;

✔ just address

no cast neededcast

needed

Examples✔ just

addresscast

needed

Page 47: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Dynamic Memory Allocation

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Programs often require memory unpredictable at compilation

Variable whose type depends on input

Array whose size depends on input, or changes with time

47

Allocate memory during run time

What to do?

Page 48: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

malloc and calloc

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Defined in <stdlib.h>

Allocate requested number of bytes

Memory is contiguous

Return pointer to first byte (type void*)

Return NULL if unsuccessful

Memory automatically released only when program exits

Programmer can release earlier

Difference: call and initialization

48

Page 49: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

double *p; p = (double*) malloc(sizeof(double)); *p=3.1415;

malloc - memory allocation

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 49

char dataType, *pc; int *pi;

printf("Type c for char, i for int: ");

scanf("%c", &dataType); if (dataType==’c’) { pc = (char*) malloc(sizeof(char)); if (pc == NULL) return 1; *pc = ’\0’; } else { pi = (int*) malloc(sizeof(int)); if (pi == NULL) return 1; *pi = 0; }

casting optional, if missing, promoted p = malloc(..);

Allocate memory for character or integer and initialize it

Allocate memory for a double and store π in it

malloc_type.c

malloc does not auto initialize

Page 50: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

double *p; p = (double*) calloc(10, sizeof(double));

calloc - Cleared Allocation

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 50

p can be viewed as pointing to array of 10 doubles

Similar to malloc Takes # items & size of each Allocates memory Initialized to 0

Equivalently:

Initialized!

Allocate and initialize memory for ten doubles

double *p; p = (double*) malloc(10*sizeof(double)); for (int i=0; i<10; i++) p[i]=0; Initialize*(p+i)=0

Page 51: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Dynamic vs. Compile-Time Memory

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Very similar, but..

Compile-time memory has name Can be addressed using name and pointers

Run-time memory has no name Can be addressed only using pointers

51

int v, *pv=&v; v=3; *pv=3; int *pw = (int*) malloc(sizeof(int)); *pw = 3; // *pw has no name

Page 52: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Garbage Collection

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language

Memory automatically released when program terminates

User can release earlier

free, defined in <stdlib.h>

Similarly for calloc

Memory size not necessary, known to operating system

52

double *p; p = (double*) malloc(sizeof(double)); // ... work with p free(p);

Page 53: Lecture 9: Pointers - University of California, San Diegoeceweb.ucsd.edu/courses/ECE15/FA_2015/lectures/lecture9.pdfLecture 8 ECE15: Introduction to Computer Programming Using the

Salaries Revisited

Lecture 8 ECE15: Introduction to Computer Programming Using the C Language 53

#include <stdio.h> #include <stdlib.h>

int main() { double *salaries; int n, i; printf(“Num employees: ”); scanf("%d", &n); // read # employees salaries = (double*) malloc(n * sizeof(double)); if (salaries == NULL) return 1; for(i=0; i<n; i++) scanf("%lf", salaries+i); // ...compute average, stdev, median, etc... free(salaries); ... }

Read # employees, allocate memory, read salaries, process, release memory

salaries = (double*) calloc(n, sizeof(double));

salaries_alloc.c

Why used malloc?

Initialized later