Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 107 - Programming for Science Lecture 30: Pointers.

Similar presentations


Presentation on theme: "CSC 107 - Programming for Science Lecture 30: Pointers."— Presentation transcript:

1 CSC 107 - Programming for Science Lecture 30: Pointers

2 Problem of the Day What is the smallest positive integer that cannot be defined in less than twenty-five syllables? The highlighted phrase has fewer than 25 syllables, so this cannot exist!

3 Today’s Goal After lecture, should know relationship between arrays and pointers  How they are similar  How they are different  How to use them both Remember: Pointers are hard

4 Pointers & Variables Variable names a memory location  Initial value is unknown  Memory location updated via assignment  Value is that stored in memory location Pointer is type of variable…  … but whose value is a memory location  Makes aliases of other variables  Used like other variables, but value is memory location

5 Declaring an Pointer Declaration includes type, name  In declaration, include asterisk before name  Variable is pointer to the requested type  Initial value is unknown int *jennifer, *bob, *mary; char *pointerToChar;

6 & Operator & operator returns address of a variable  Used with variables, including array elements  Cannot be used with anything else long x, a[20], b[4][5]; long *y, *z; y = &x; z = &(a[2]); y = &(b[3]); z = &(b[3][2]); y = &a; z = b; y = &(x[1]); z = a;

7 Array Kinda is a Pointer int y,x[10]; x[4] = 5; y = x[0]; This really means: int y; // Get memory location & name it y int x[10]; // Get 11 locations: 1 for x & 10 for elements; // Store location of first element in x x[4] = 5; // Get memory location in x, skip past // 4 memory locations, and store a 5 y = x[0]; // Get location from x’s memory location, move // 0 locations over, and copy value at that // location into location named y

8 Pointers versus Arrays Value of either type of variable is memory location  Can assign pointer to array and vice versa Either can use * or [] to access value  *p is a synonym for p[0] But do not take this too far  Only array variable has an initial value  Rarely use array to alias data

9 Pointers and Arrays char x[4] = {‘p’, ‘o’, ‘t’, ‘s’}; char *y = &(x[1]); printf(“%c%c%c%c\n”, x[0], x[1], x[2], x[3]); *y = ‘a’; *x = ‘c’; printf(“%c%c%c%c\n”, x[0], x[1], x[2], x[3]); y = x; y[2] = ‘p’; x[1] = ‘o’; printf(“%c%c%c%c\n”, x[0], x[1], x[2], x[3]);

10 Your Turn Get back into groups and complete the daily activity

11 For Next Lecture Read! Keep up with weekly assignments


Download ppt "CSC 107 - Programming for Science Lecture 30: Pointers."

Similar presentations


Ads by Google