Week 5 - CS50cdn.cs50.net/2007/fall/lectures/5/week5.pdf · 2012. 8. 22. · Microsoft PowerPoint -...

Post on 29-Sep-2020

0 views 0 download

Transcript of Week 5 - CS50cdn.cs50.net/2007/fall/lectures/5/week5.pdf · 2012. 8. 22. · Microsoft PowerPoint -...

0

Computer Science 50Introduction to Computer Science I

Harvard College

David J. Malanmalan@post.harvard.edu

Week 5

1

“iPhone / iPod touch v1.1.1 jailbreak code posted”

Image from http://www.engadget.com/2007/10/21/iphone-ipod-touch-v1-1-1-jailbreak-code-posted/.

2

Hexadecimal

0xdeadbeef

3

Passing by Value

void

swap(int a, int b)

{

int tmp;

tmp = a;

a = b;

b = tmp;

}see

buggy3.c

4

Passing by Reference

void

swap(int *a, int *b)

{

int tmp;

tmp = *a;

*a = *b;

*b = tmp;

}see

swap.c

5

The StackRevisited

6

Pointers

int i, j;

int *p;

Image from http://computer.howstuffworks.com/c22.htm.

7

Pointers

p = &i;

Image from http://computer.howstuffworks.com/c22.htm.

8

Pointers

*p = 5;

Image from http://computer.howstuffworks.com/c22.htm.

9

Arrays as Pointersint i;

int a[5];

int *p = a;

Image from http://computer.howstuffworks.com/c22.htm.

seecompare{1,2}.c, pointers{1,2}.c

10

Dynamic Memory Allocationmalloc

// instantiate memo

memo = (long long *) malloc((n+1) * sizeof(long long));

if (memo == NULL)

{

printf("Out of memory!\n");

return 2;

}

[...]

// free up memory

free(memo); seefs4.c, copy.c

11

Memory ManagementRevisited

12

CS 50’s LibraryRevisited

seescanf{1,2,3}.c, ~cs50/pub/releases/cs50/cs50.{c,h}

bool

string

char GetChar();

double GetDouble();

float GetFloat();

int GetInt();

long long GetLongLong();

string GetString();

13

struct(and header files)

seestructs1.c

typedef struct

{

int id;

char * name;

char * house;

}

student;

14

File I/O

seestructs2.c

fopen/fclose

fscanf/fprintf

fread/fwrite

feof

...

15

16

Computer Science 50Introduction to Computer Science I

Harvard College

David J. Malanmalan@post.harvard.edu

Week 5