CSSE221: Software Dev. Honors Day 27

Post on 13-Jan-2016

28 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

CSSE221: Software Dev. Honors Day 27. Announcements Projects turned in? The 2 required Angel surveys are due by 9 pm tonight. Graded based on thoughtful responses Questions? We will cover everything you need to know to do parts 1-3 of C Projects over the weekend. This week: Intro to C. - PowerPoint PPT Presentation

Transcript

CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 27Day 27

AnnouncementsAnnouncements Projects turned in?Projects turned in? The 2 required Angel surveys are due The 2 required Angel surveys are due

by 9 pm tonight. by 9 pm tonight. Graded based on thoughtful responsesGraded based on thoughtful responses

Questions?Questions?

We will cover everything you need to We will cover everything you need to know to do parts 1-3 of C Projects know to do parts 1-3 of C Projects over the weekend.over the weekend.

This week: Intro to CThis week: Intro to C Monday:Monday:

Project dayProject day Tuesday:Tuesday:

Introduction to CIntroduction to C Thursday:Thursday:

1.1. (15 min) Simple C File I/O(15 min) Simple C File I/O2.2. (30 min) Pointers and using them to (30 min) Pointers and using them to

change arguments passed to change arguments passed to functions.functions.

3.3. (20 min) Arrays and pointer arithmetic(20 min) Arrays and pointer arithmetic4.4. (15 min) Dynamic memory allocation(15 min) Dynamic memory allocation

1. File handling1. File handlingOpen a file using fopen Returns a file pointer to access the file: FILE* Modes:

“r” (read) “w” (write) “a” (append)

A few more file handling functions: fprintf - write to the stream in the format specified. fscanf - read from the stream. Returns the number of items

read, which can be used in a loop termination condition. fclose - close the file and return the file pointer.

fgets - gets a whole line at a time feof - returns true (1) after an fscanf fails (useful for

error-checking)

Defined in stdio.h (fgets in ctype.h) Let’s try one together (hidden slides available if you want more info later)

2. Can functions modify 2. Can functions modify arguments?arguments?

In Java, no! (pass by value)In Java, no! (pass by value) Consider this function:Consider this function:void increment(int takeMeHigher){void increment(int takeMeHigher){

takeMeHigher ++;takeMeHigher ++;

}}

How is this C function invoked?How is this C function invoked? increment(up);increment(up);

Will calling the function change the Will calling the function change the values of the arguments values of the arguments upup??

References to simple References to simple variablesvariables

Pointers need to be used to change Pointers need to be used to change the value of an argumentthe value of an argument

A A pointerpointer is a variable that holds the is a variable that holds the addressaddress of a variable of a variable

. . .

int num = 4;int *pNum;pNum = #*pNum == num ==

4

double change = 0.45;

double *pChange;pChange = &change*pChange = .62; // makes change

== .624num:

0.45change:pNum: pChange:

//// 0.62

Recap: Pointer Recap: Pointer Operators, &Operators, &

The The addressaddress operator, operator, &&:: &var &var gives the address where gives the address where varvar's value 's value

is storedis stored Examples:Examples:

xPtr = &x;xPtr = &x; /* Read "/* Read "xPtrxPtr gets the address of gets the address of xx" */" */

dPtr = &d;dPtr = &d; /* Read "/* Read "ddPtrPtr gets the gets the address of address of dd" */" */

Recap: Pointer Recap: Pointer Operators, *Operators, *

Use Use ** two ways: two ways: In type declarations, In type declarations, ** says that the name says that the name

refers to address of something: refers to address of something: int *xPtr; int *xPtr; double *dPtr;double *dPtr;

In expressions, In expressions, *var*var gives the "thing" gives the "thing" pointed to by pointed to by varvar

printf("%d", *xPtr);printf("%d", *xPtr);

*dPtr = 3.14159;*dPtr = 3.14159;

The format string, "%d", says that we want to print an int. *xPtr is the thing pointed to by xPtr. That is, *xPtr is the value of x.

This says that the thing pointed to by dPtr should get the value 3.14159. So the result is the same as d = 3.14159.

How do we modify increment() so How do we modify increment() so that it actually changes the values of that it actually changes the values of its argument?its argument? By passing pointers to the parameters to be By passing pointers to the parameters to be

changedchanged You’ll do this with increment and swap You’ll do this with increment and swap

shortly.shortly.

3. Pass pointers if you 3. Pass pointers if you want to change want to change

argumentsarguments

Hands-on activityHands-on activity

Checkout project Checkout project CDemos/PointerSandbox from SVNCDemos/PointerSandbox from SVN

Let’s start on Q1 togetherLet’s start on Q1 together Then finish through Q5. Then finish through Q5.

Pass pointers if you want Pass pointers if you want to change argumentsto change arguments

/* Actually modifies the values of the variables its /* Actually modifies the values of the variables its parameters point to. */parameters point to. */

void swap(int* x, int* y) {void swap(int* x, int* y) {

int temp = *x;int temp = *x;

*x = *y;*x = *y;

*y = temp;*y = temp;

}}

Note also what we passed: swap(Note also what we passed: swap(&&a, a, &&b)b)

Another look at the use Another look at the use of & in scanfof & in scanf

int x, y;int x, y; scanf("%d %d", &x, &y);scanf("%d %d", &x, &y); What would happen if we used What would happen if we used yy

instead of instead of &y&y??

Using Pointers to Using Pointers to "Return" Multiple "Return" Multiple

ResultsResults C only allows us to C only allows us to return return one value from a one value from a

functionfunction Can use pointers to return multiplesCan use pointers to return multiples Suppose we want a function that takes an array Suppose we want a function that takes an array

and returns the mean, min, and max values:and returns the mean, min, and max values: void calcStats(double[ ] values, int count, void calcStats(double[ ] values, int count,

double *mean, double *min, double *max) {double *mean, double *min, double *max) {/* … some logic omitted …*//* … some logic omitted …*/*mean = meanValue; *mean = meanValue; *min = minValue;*min = minValue;*max = maxValue;*max = maxValue;

}} This says that the thing pointed to by mean should get the value stored in meanValue.

Pointer PitfallsPointer Pitfalls

Don't try to dereference an unassigned Don't try to dereference an unassigned pointer:pointer: int *p;int *p;

*p = 5; /* oops! */*p = 5; /* oops! */ Pointer variables must be assigned Pointer variables must be assigned addressaddress

values.values. int x;int x;

int *p = x; /* oops, RHS should be &x */int *p = x; /* oops, RHS should be &x */ Be careful how you incrementBe careful how you increment

*p +=1; /* is not the same as … */*p +=1; /* is not the same as … */ *p++;*p++;

Pointers to structs…and a Pointers to structs…and a nifty shorthandnifty shorthand

Passing pointers to structs to methods is Passing pointers to structs to methods is more efficient (the whole struct doesn’t more efficient (the whole struct doesn’t get copied):get copied):

juan = makeStudent(“Juan”, 2007, 3.2);juan = makeStudent(“Juan”, 2007, 3.2);

printGPA(&juan);printGPA(&juan);

void printGPA(Student *s) {void printGPA(Student *s) {printf(“%4.2lf\n”, printf(“%4.2lf\n”, (*s).gpa(*s).gpa););

}}

typedef structtypedef struct {{charchar *name;*name;intint year;year;doubledouble gpa; gpa;

} Student;} Student;

printf(“%4.2lf\n”, printf(“%4.2lf\n”, s->gpas->gpa););

If you need to dereference a pointer to a struct

and use the dot operator, use -> instead: (*s).f

== s->f

BreakBreak

Starring Starring BinkyBinky!! (See (See

http://cslibrary.stanford.edu/104/http://cslibrary.stanford.edu/104/))

4. Arrays and Pointer 4. Arrays and Pointer ArithmeticArithmetic

int a[10];

a[0] a[1] a[9]

a:

int *pa;

pa = &a[0];

a[0] a[1] a[9]

a:

pa: pa + 1: pa + 5:

See below instead

So*(pa + 1) == ______ and pa + 1 == ______

And pa and a can almost be used interchangeably…Except the value of pa can be modified, but a can’t.

Arrays as function Arrays as function parametersparameters

int [ ] and int * are equivalent, when used int [ ] and int * are equivalent, when used as parameters in a function definition.as parameters in a function definition. void f (int a[], int count) { …void f (int a[], int count) { … void f (int *a, int count) { …void f (int *a, int count) { …

Note that in neither case can we know Note that in neither case can we know the size of the array, unless it is passed the size of the array, unless it is passed in as a separate parameter.in as a separate parameter.

In either case, the 5In either case, the 5thth element of element of aa can be can be referred to asreferred to as a[5]a[5] *(a+5)*(a+5)

Back to the Hands-on Back to the Hands-on activityactivity

First, let’s see in the debugger that First, let’s see in the debugger that arrays and pointers are the same.arrays and pointers are the same.

Q6 asks you to fill an array with Q6 asks you to fill an array with data, then display it. I want you to data, then display it. I want you to do this using subscripts, then again do this using subscripts, then again using pointer arithmetic.using pointer arithmetic.

5. Dynamic Memory 5. Dynamic Memory AllocationAllocation

Explicit allocation and de-Explicit allocation and de-allocation by user using allocation by user using malloc() and free().malloc() and free().

Functions:Functions:(void *) malloc(size_t size);(void *) malloc(size_t size);void free(void *ptr);void free(void *ptr);bytes sizeof(type)bytes sizeof(type)

void* is a “generic” pointer. void* is a “generic” pointer. malloc returns a chunk of malloc returns a chunk of memory that can be used memory that can be used as any type. We must cast as any type. We must cast the results of malloc to the the results of malloc to the type that we want, like type that we want, like (double*).(double*).

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

int *ptr; /* allocate space to hold 4

ints */

/* do stuff with the data */ ptr[3] = 4; //or *(ptr+3)=4;

/* free up the allocated space */

return 0;}

5. Dynamic Memory 5. Dynamic Memory AllocationAllocation

Explicit allocation and de-Explicit allocation and de-allocation by user using allocation by user using malloc() and free().malloc() and free().

Functions:Functions:(void *) malloc(size_t size);(void *) malloc(size_t size);void free(void *ptr);void free(void *ptr);bytes sizeof(type)bytes sizeof(type)

void* is a “generic” pointer. void* is a “generic” pointer. malloc returns a chunk of malloc returns a chunk of memory that can be used memory that can be used as any type. We must cast as any type. We must cast the results of malloc to the the results of malloc to the type that we want, like type that we want, like (double*).(double*).

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

int *ptr; /* allocate space to hold 4

ints */

ptr=(int*)malloc(4*sizeof(int));

/* do stuff with the data */ ptr[3] = 4; //or *(ptr+3)=4;

/* free up the allocated space */free(ptr);

return 0;}

int *ptr;

?

ptr

4000

ptr = (int*)malloc(4 * sizeof(int)); //Address 6000 on the heap is allocated

60006000 60046004 60086008 60126012

?? ?? ?? ??6000

*ptr=4;

4

free(ptr);

Final note:

If there is no more memory available, malloc

will return NULL, so it’s good to check for this

case.

Last hands-on activityLast hands-on activity

Q7 asks you to write code that uses Q7 asks you to write code that uses a dynamic array.a dynamic array.

top related