Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.

Similar presentations


Presentation on theme: "CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight."— Presentation transcript:

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

2 This week: Intro to C Monday: Monday: Project day Project day Tuesday: Tuesday: Introduction to C Introduction to C Thursday: Thursday: 1. (15 min) Simple C File I/O 2. (30 min) Pointers and using them to change arguments passed to functions. 3. (20 min) Arrays and pointer arithmetic 4. (15 min) Dynamic memory allocation

3 File handling What operations should we perform on a file? What operations should we perform on a file?

4 1. File handling Open 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)

5 /* Declare a file pointer called inFile */ _________________________________________ /* open a file called “test.txt” for writing */ ________________________________________ /* No exception handling – so check if file opened successfully */ if(inFile == NULL){ exit(1); /* exit program – don’t return to calling function */ } /* Write a string “Hello there” to the file */ /* Function prototype: int fprintf(FILE *stream, const char *format, /* args*/...); */ ______________________________________________________________ /* Write the value of the int variable “count” followed by the value of the float variable “price” to the file. Separate the two values with space */ ___________________________________________________________________ /* Don’t forget to release file pointer */ ____________________________________

6 /* Declare a file pointer called inFile */ FILE *inFile;______________________________________ /* open a file called “test.txt” for writing */ inFile = fopen(“test.txt”, “w”);______________________________________ /* No exception handling – so check if file opened successfully */ if(inFile == NULL){ exit(1); /* exit program – don’t return to calling function */ } /* Write a string “Hello there” to the file */ /* Function prototype: int fprintf(FILE *stream, const char *format, /* args*/...); */ fprintf(inFile, “Hello there”); /* Write the value of the int variable “count” followed by the value of the float variable “price” to the file. Separate the two values with space */ fprintf(inFile, “%i %f”, count, price); /* Don’t forget to close the file and release the file pointer */ fclose(inFile);

7 Reading till end of file /* Using a while loop, read data from a file that has only integers until there is no more data to read */

8 Reading till end of file /* Using a while loop, read data from a file that has only integers until there is no more data to read */ int count = 0; while (fscanf(input_file, "%d", &int1) > 0) { count++; count++; printf("%d \n", int1); // Do something with the data printf("%d \n", int1); // Do something with the data fscanf(input_file, "%d", &int1); // Try reading again for next item fscanf(input_file, "%d", &int1); // Try reading again for next item } // Go back to while to test if more // data was read

9 2. Can functions modify arguments? In Java, no! (pass by value) In Java, no! (pass by value) Consider this function: Consider this function: 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 values of the arguments up? Will calling the function change the values of the arguments up?

10 References to simple variables Pointers need to be used to change the value of an argument Pointers need to be used to change the value of an argument A pointer is a variable that holds the address of a variable A pointer is a variable that holds the address of a variable... int num = 4; int *pNum; pNum = # *pNum == num == 4 double change = 0.45 ; double *pChange; pChange = &change *pChange =.62; // makes change ==.62 4 num: 0.45 change:pNum:pChange: //// 0.62

11 Recap: Pointer Operators, & The address operator, &: The address operator, &: &var gives the address where var's value is stored &var gives the address where var's value is stored Examples: Examples: xPtr = &x;/* Read "xPtr gets the address of x" */ xPtr = &x;/* Read "xPtr gets the address of x" */ dPtr = &d; /* Read "dPtr gets the address of d" */ dPtr = &d; /* Read "dPtr gets the address of d" */

12 Recap: Pointer Operators, * Use * two ways: Use * two ways: In type declarations, * says that the name refers to address of something: int *xPtr; double *dPtr; In type declarations, * says that the name refers to address of something: int *xPtr; double *dPtr; In expressions, *var gives the "thing" pointed to by var In expressions, *var gives the "thing" pointed to by var 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.

13 How do we modify increment() so that it actually changes the values of its argument? How do we modify increment() so that it actually changes the values of its argument? By passing pointers to the parameters to be changed By passing pointers to the parameters to be changed You’ll do this with increment and swap shortly. You’ll do this with increment and swap shortly. 3. Pass pointers if you want to change arguments

14 Hands-on activity Checkout project CDemos/PointerSandbox from SVN Checkout project CDemos/PointerSandbox from SVN Let’s start on Q1 together Let’s start on Q1 together Then finish through Q5. Then finish through Q5.

15 Pass pointers if you want to change arguments /* Actually modifies the values of the variables its parameters point to. */ void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } Note also what we passed: swap(&a, &b)

16 Another look at the use of & in scanf int x, y; int x, y; scanf("%d %d", &x, &y); scanf("%d %d", &x, &y); What would happen if we used y instead of &y? What would happen if we used y instead of &y?

17 Using Pointers to "Return" Multiple Results C only allows us to return one value from a function C only allows us to return one value from a function Can use pointers to return multiples Can use pointers to return multiples Suppose we want a function that takes an array and returns the mean, min, and max values: Suppose we want a function that takes an array and returns the mean, min, and max values: void calcStats(double[ ] values, int count, double *mean, double *min, double *max) { /* … some logic omitted …*/ *mean = meanValue; *min = minValue; *max = maxValue; } void calcStats(double[ ] values, int count, double *mean, double *min, double *max) { /* … some logic omitted …*/ *mean = meanValue; *min = minValue; *max = maxValue; } This says that the thing pointed to by mean should get the value stored in meanValue.

18 Pointer Pitfalls Don't try to dereference an unassigned pointer: Don't try to dereference an unassigned pointer: int *p; *p = 5; /* oops! */ int *p; *p = 5; /* oops! */ Pointer variables must be assigned address values. Pointer variables must be assigned address values. int x; int *p = x; /* oops, RHS should be &x */ int x; int *p = x; /* oops, RHS should be &x */ Be careful how you increment Be careful how you increment *p +=1; /* is not the same as … */ *p +=1; /* is not the same as … */ *p++; *p++;

19 Pointers to structs…and a nifty shorthand Passing pointers to structs to methods is more efficient (the whole struct doesn’t get copied): juan = makeStudent(“Juan”, 2007, 3.2); printGPA(&juan); void printGPA(Student *s) { printf(“%4.2lf\n”, (*s).gpa); } typedef struct { char *name; int year; double gpa; } Student; printf(“%4.2lf\n”, s->gpa); If you need to dereference a pointer to a struct and use the dot operator, use -> instead: (*s).f == s->f

20 Break Starring Binky! Starring Binky! (See http://cslibrary.stanford.edu/104/) (See http://cslibrary.stanford.edu/104/)http://cslibrary.stanford.edu/104/

21 4. Arrays and Pointer Arithmetic 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.

22 Arrays as function parameters int [ ] and int * are equivalent, when used as parameters in a function definition. int [ ] and int * are equivalent, when used 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 the size of the array, unless it is passed in as a separate parameter. Note that in neither case can we know the size of the array, unless it is passed in as a separate parameter. In either case, the 5 th element of a can be referred to as In either case, the 5 th element of a can be referred to as a[5] a[5] *(a+5) *(a+5)

23 Back to the Hands-on activity First, let’s see in the debugger that arrays and pointers are the same. First, let’s see in the debugger that arrays and pointers are the same. Q6 asks you to fill an array with data, then display it. I want you to do this using subscripts, then again using pointer arithmetic. Q6 asks you to fill an array with data, then display it. I want you to do this using subscripts, then again using pointer arithmetic.

24 5. Dynamic Memory Allocation Explicit allocation and de-allocation by user using malloc() and free(). Functions: (void *) malloc(size_t size); void free(void *ptr); bytes sizeof(type) void* is a “generic” pointer. malloc returns a chunk of memory that can be used as any type. We must cast the results of malloc to the type that we want, like (double*). #include 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; }

25 5. Dynamic Memory Allocation Explicit allocation and de-allocation by user using malloc() and free(). Functions: (void *) malloc(size_t size); void free(void *ptr); bytes sizeof(type) void* is a “generic” pointer. malloc returns a chunk of memory that can be used as any type. We must cast the results of malloc to the type that we want, like (double*). #include 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; }

26 int *ptr; ? ptr 4000 ptr = (int*)malloc(4 * sizeof(int)); //Address 6000 on the heap is allocated 6000600460086012 ???? 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.

27 Last hands-on activity Q7 asks you to write code that uses a dynamic array. Q7 asks you to write code that uses a dynamic array.


Download ppt "CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight."

Similar presentations


Ads by Google