Presentation is loading. Please wait.

Presentation is loading. Please wait.

C language issues CSC 172 SPRING 2002 EXTRA LECTURE.

Similar presentations


Presentation on theme: "C language issues CSC 172 SPRING 2002 EXTRA LECTURE."— Presentation transcript:

1 C language issues CSC 172 SPRING 2002 EXTRA LECTURE

2 C and JAVA For the most part, they are very similar However one major difference is the syntax of indirection JAVA hides indirection (references) C makes indirection explicit (pointers)

3 Pointers in C char c; // in C any byte can be a char If c is a char and p is a pointer that points to it The unary operator “&” gives the address of an object p = &c ; p c

4 Indirection/dereferencing The unary operator “*” is the dereferencing operator 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 zero ip = &z[0]; // ip now points to z[0];

5 Pointers and function args C passes arguments to functions by value void swap (int x, int y) { /* does not work */ int temp; temp = x; x = y; y = temp; }

6 We have to pass in pointers swap(&a,&b); void swap (int *px, int *py) { /* works */ int temp; temp = *px; *px = *py; *py = temp; } In caller: a: b: In swap: py: px:

7 Pointers and Arrays int a[10]; a: a[0]a[1]a[9]

8 Pointers and Arrays int *pa; pa = &a[0]; a: a[0]a[1]a[9] pa: pa+1 pa+2 pa = a ; // equivalent

9 Structures Back in the old days, before classes and OO, when dinosaurs had to program, they wrote? struct point { int x; int y; }

10 Using structs Syntax: structure-name.member struct point pt; pt.x=3; pt.y=4;

11 Pointers to structs struct point origin, *pp; pp = &origin; Then, the following are equivalent origin.x (*pp).x pp->x


Download ppt "C language issues CSC 172 SPRING 2002 EXTRA LECTURE."

Similar presentations


Ads by Google