Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computing Science Thompson Rivers University

Similar presentations


Presentation on theme: "Computing Science Thompson Rivers University"— Presentation transcript:

1 Computing Science Thompson Rivers University
C: Advanced Topics Computing Science Thompson Rivers University

2 Unit Learning Objectives
Use pointers and references. Use pointers for dynamic memory management. Use open(), read(), write(), close(), and FILE* functions to manipulate files. Use user-defined data structures. More coming C: Advanced Topics

3 Unit Contents Pointers and Arrays Structures Input and Output
C: Advanced Topics

4 1. Pointers and Arrays C: Advanced Topics

5 Pointers and Addresses
A pointer is a variable that contains the address of a variable. Pointers and arrays are very closely related. int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to int */ ip = &x; /* ip now points to x */ y = *ip; /* y is now 1 */ *ip = 0; /* x is now 0 */ ip = &z[1]; /* ip now points to z[1] */ Declaration of a pointer variable: * Reference operator: & Indirection operator (oac dereference operator): * C: Advanced Topics

6 Varible name value address E
x 1 A ... y 2 B z E C ip ? D z[0] z[1] F z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; C: Advanced Topics

7 Varible name value address E
x 1 A ... y 2 B z E C ip D z[0] ? z[1] F z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; C: Advanced Topics

8 Varible name value address E
x 1 A ... y B z E C ip D z[0] ? z[1] F z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; C: Advanced Topics

9 Varible name value address E
x A ... y 1 B z E C ip D z[0] ? z[1] F z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; C: Advanced Topics

10 F Varible name value address x A ... y 1 B z E C ip D z[0] ? z[1] z[2]
A ... y 1 B z E C ip F D z[0] ? z[1] z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; *ip = 5; C: Advanced Topics

11 F Varible name value address x A ... y 1 B z E C ip D z[0] ? z[1] 5
A ... y 1 B z E C ip F D z[0] ? z[1] 5 z[2] z[3] int x = 1; int y = 2; int z[10]; int *ip; ip = &x; y = *ip; *ip = 0; ip = &z[1]; *ip = 5; C: Advanced Topics

12 Pointers and Function Arguments
How to write a function that swaps the values stored in two variables? swap(a, b); ... void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } Is the above function correct? Why? At assembly time, this function call will be expanded to create three variables in the stack area. The stack pointer will be increased as the result. The return statement is hidden. At assembly time, the return statement will be expanded to delete three variables in the stack area. The stack pointer will be decreased as the result. C: Advanced Topics

13 Varible name value address
swap(a, b); ... void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } Varible name value address a 1 A ... b 2 B x C y D temp ? E At this moment C: Advanced Topics

14 Varible name value address
swap(a, b); ... void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } Varible name value address a 1 A ... b 2 B x C y D temp E At this moment C: Advanced Topics

15 Varible name value address
swap(a, b); ... void swap(int x, int y) { int temp; temp = x; x = y; y = temp; } Varible name value address a 1 A ... b 2 B At this moment C: Advanced Topics

16 How to write a function that swaps the values stored in two variables?
swap(&a, &b); ... void swap(int *px, int* py) { int temp; temp = ???; ???; ??? = temp; } Varible name value address a 1 A ... b 2 B px C py D tmp ? E At this moment C: Advanced Topics

17 Varible name value address
swap(&a, &b); ... void swap(int *px, int* py) { int temp; temp = *px; *px = *py; *py = temp; } Varible name value address a 1 A ... b 2 B px C py D tmp E C: Advanced Topics

18 Varible name value address 2
swap(&a, &b); ... void swap(int *px, int* py) { int temp; temp = *px; *px = *py; *py = temp; } Varible name value address a 2 A ... b B px C py D tmp 1 E C: Advanced Topics

19 Varible name value address 1
swap(&a, &b); ... void swap(int *px, int* py) { int temp; temp = *px; *px = *py; *py = temp; } Varible name value address a 2 A ... b 1 B px C py D tmp E C: Advanced Topics

20 Varible name value address
swap(&a, &b); ... void swap(int *px, int* py) { int temp; temp = *px; *px = *py; *py = temp; } Varible name value address a 2 A ... b 1 B C: Advanced Topics

21 int *test; int number = 20; test = &number; printf(“%d, %d, %p, %p\n”, number, *test, test, &test); // the content of the var pointed by test // the content of test *test = 30; printf(“Enter an integer: ”); scanf(“%d”, &number); // the address of number printf(“%d, %d, %d, %p, %p, %p\n”, number, *test, *(&number), test, &test, &number); // the content pointed by test // the content pointed // by the address of number // the address of test // the address of number C Programming

22 Can you write a function to read multiple integers into an array?
int data[10]; getint(data, 10); // read 10 integers into data[] ... ??? getint(???, ???) { ??? // using scanf() } C: Advanced Topics

23 Pointers and Arrays Strong relation between and pointers
float *px; // px is ready to store an address. float x[10]; // x represents 10 float type variables, // x[0], x[1], ..., x[9], that are // alocated in cosecutive memory area. // x has the address of x[0]. float y; x[0] = 2; x[1] = 3; x[2] = 4; x[3] = 5; x[4] = 6; x[5] = 7; px = x; // the same data type? y = *px; printf(“%f, %f, %f\n”, x[0], *px, y); // ??? px = &x[2]; y = *(px+2); C: Advanced Topics

24 int num[] and int *num are equivalent.
int number[10]; printf(“%p\n”, &(number[0])); printf(“%p\n”, &(number[5])); printf(“%p\n”, number); // related to reference printf(“%p\n”, number + 5); // the address of number[5] // not 5 * 4 newval(number); ... void newval(int num[]) { num[0] = 5; ... }, or void newval(int* num) { *num = 5; *(num+1) = 10; num[2] = 20; ... } int num[] and int *num are equivalent. C Programming

25 Why do we need to use pointer variables?
int number[10]; int *p, *q; *p = 10; // Is it wrong? p = number; q = &number[0]; number[0] = 2; number[1] = 9; number[2] = 5; printf(“%p, %p\n”, p, q); printf(“%d, %d, %d, %d\n”, *(p+1), p[1], *(q+1), q[1]); Pointer variables and array variables can be used interchangeably. Why do we need to use pointer variables? C Programming

26 Do we really need to use pointers? Dynamic memory management
#include <stdlib.h> void *malloc(int size); // allocate size bytes // and return the addr void free(void *); // free the memory space ... int *p, n; scanf(“%d”, &n); // space for n-many integer variables. p = (int*)malloc(sizeof(int) * n); p[0] = 10; *(p+1) = 20; *(p+2) = 30; p++; *p = 4; C Programming

27 Character Pointers #include <string.h.> gets(), puts() strcpy(), strlen(), strcmp(), strcat(), ... toupper(), ... C: Advanced Topics

28 sprintf(tmp, “course name is %s.”, name);
char name[256], tmp[256]; name[0] = ‘C’; name[1] = ‘O’; name[2] = ‘M’; name[3] = ‘P’; name[4] = ‘\0’; // it is very important. name[5] = ‘ ’; name[6] = ‘2’; name[7] = ‘1’; name[8] = ‘3’; name[9] = ‘0’; name[10] = ‘\0’; // it is very important. printf(“course number = %s\n”, name); printf(“%p\n”, name); printf(“course number = %s\n”, &(name[5])); scanf(“%s”, name); // not &name sprintf(tmp, “course name is %s.”, name); C Programming

29 Pointer Arrays: Pointers to Pointers
void f(int *x[13]); // 13 int* variables void f(int (*x)[13]); // pointer to an array of 13 ints // equivalent to int x[][13] Command-line arguments int main(int argc, char *argv[]); argc the number of arguments argv[0] the program name, e.g., a.out argv[1] the first argument from the user E.g., $ ./a.out test this comp argc: 4 argv[0]: “./a.out” argv[1]: “test C: Advanced Topics

30 2. Structures User-defined data structure
struct student_rcd { // class without methods in Java int student_number; char name[128]; ... }; struct student_rcd record[10], *rp; struct student_rcd test; // how to declare a struct variable test.student_number = 10; // how to access a member print_rcd(test); read_rcd(&test); record[0].student_number = 5; rp = (struct student_rcd *)malloc(sizeof(struct student_rcd) * 3); rp->student_number = 20; // Be careful with the “->” (*(rp+1)).student_number = 40; rp[2].student_number = 30; C: Advanced Topics

31 void print_rcd(struct student_rcd rcd) { printf(“Number: %d\n”, rcd
void print_rcd(struct student_rcd rcd) { printf(“Number: %d\n”, rcd.student_number); printf(“Name: %s\n”, rcd.name); // name is an array. // not &(rcd.name) } void read_rcd(struct student_rcd *rcd) printf(“Enter number: “); scanf(“%d”, &(rcd->student_number)); // reference rqd printf(“Enter name: “); scanf(“%s”, rcd->name); // name is an array. // not &(rcd->name) C: Advanced Topics

32 Self-Referential Structures
struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ struct tnode *parent; }; struct tnode root; root.left = (struct tnode *)malloc(...); C: Advanced Topics

33 Typedef typedef int Length; // Now Length is a data type. typedef char *String; // Now String is a data type. typedef struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left, *right; /* children */ struct tnode *parent; } Treenode; // Now Treenode is a data type. ... Length len, maxlen; Length *lengths[]; String p, lineptr[MAXLINES]; Treenode tnode; p = (String) malloc(100); // p[0], ..., p[99] C: Advanced Topics

34 Example C: Advanced Topics
struct Student { char name[128]; int number; Student *next; }; typedef struct Student Student; Student *head = null; // important Student *new, *tmp; new = create_student(); // create a record, read data from the user, // store them into the record add_student(head, new); // add the new record at the end of the list tmp = find_student(head, ); // find the record whose number is .. printf(“%d: %s\n”, tmp->number, tmp->name); // print the record delete_student(head, ); Name Number next Name Number next Name Number next Head null C: Advanced Topics

35 ... create_student( ... ) // create a record, read data from the user, { // store them into the record Student *new = ( ... )malloc( ... ); scanf(“%s”, ...) // read name scanf(“%d”, ...) // read number new->next = null; // very important; (*new).next = null return ...; }; ... add_student(... head, ... new) // add the new record at the end of the list { Student *tmp; if (head == null) // when there is no record yet head = new; else { while((*tmp).next != null) // move to the last record tmp = (*tmp).next; // You cannot use array syntaxes (*tmp).next = new; // because the Student objects were not } // consecutively created. return; } C: Advanced Topics

36 find_student(. head,. no) // find the record { Student
... find_student(... head, ... no) // find the record { Student *tmp; tmp = head; while(tmp != null) { if ((... == no) break; tmp = ...; } ... delete_student(... head, ... no) ... C: Advanced Topics

37 Unions For polymorphism union u_tag { // the shared storage int ival;
float fval; char *sval; } ... int utype; union u_tag u; u.ival = 20; if (utype == INT) printf("%d\n", u.ival); if (utype == FLOAT) printf("%f\n", u.fval); if (utype == STRING) printf("%s\n", u.sval); else printf("bad type %d in utype\n", utype); C: Advanced Topics

38 3. Input and Output Standard input from keyboard
$ prog < infile input redirection $ otherprog | prog pipe <stdio.h> int getchar() int putchar(int c) C: Advanced Topics

39 Formatted input int scanf (char *format, arg1, arg2, ...) // from stdin int sscanf (char *string, char *format, arg1, arg2, ...); // from string The arguments must be references. C: Advanced Topics

40 File Access #include <stdio.h> FILE *in, *out; // FILE is defined in <stdio.h> in = fopen(“in_filename”, “r”); // mode: r, w, a, r+, w+, a+ if (in == NULL) ... out = fopen(“out_filename”, “w”); fclose(in); fprintf(out, “format ...”, variables...); fscanf(...); fgets(...); int fseek(FILE*, long, SEEK_SET or SEEK_CURRENT or SEEK_END); // move file position pointer int fwrite(void*, int memb_size, int no_memb, FILE*); int fread(void*, int memb_size, int no_memb, FILE*); C: Advanced Topics

41 int fputcs(char*, FILE*); int fgetc(FILE*);
int fputc(int, FILE*); int fputcs(char*, FILE*); int fgetc(FILE*); int fscanf(FILE*, char* format, ...); int fprintf(FILE*, char* format, ...); Examples: A file copy program, using fopen(), fseek(), fwrite(), fread(), fclose(). Files containing student records struct student { ... }; struct student record; FILE *fp = fopen(“test”, “w+”); // read and write; file truncated; fwrite(&record, sizeof(struct student), 1, fp); fread(&record, sizeof(struct student), 1, fp); C: Advanced Topics

42 How to obtain the current position:: long ftell(FILE*);
C: Advanced Topics

43 Error Handling – Stderr and Exit
fprintf(stderr, char*, ...); exit(int); // non zero means error C: Advanced Topics

44 math.h Some MATH related functions # include <math.h>
double sqrt(double); double pow(double, double); double fabs(double); ... Link with –lm -lm means libm.a, that contains math utilities, is used $ gcc program3-5.c –lm C Programming


Download ppt "Computing Science Thompson Rivers University"

Similar presentations


Ads by Google