# Pointers

Document Sample

```					       CS110: Lecture 23
Object Oriented Programming
+ Misc. Lost Details
Jack Tumblin
jet@cs.northwestern.edu
I hope you:
–   Have completed PA-4, due today
–   Used Blackboard to turn in PA-4
–   Have started on Project 5, DUE WED. DEC 3
–   Know all about structures & pointers:
Chap. 12 except 12-8
Question from TAs
• Infinite loops:
what happens if you do this? eventually?

int main()
{
int i;

for(i = 0; i > -1; i++)
{
// do something useful...
}
return 0;
}
Question from TAs
Variable i keeps growing;
• Infinite loops: the set of integers isn't infinite: 31
only holds numbers from -231 to +2 .
what happens if you do this? eventually?
when i reaches +231, then
int main()
i++ will produce i == -231,
{
AND THEN THE LOOP STOPS!
int i;

for(i = 0; i > -1; i++)
{
// do something useful...
}
return 0;
}
NEW! Blackboard turn-in
• For project 4 and 5, use 'Digital Drop Box' :
Blackboard: [ Tools ] button,
Digital Drop Box,

• Be sure to SEND, don't just ADD FILE

• No need to turn in paper printouts
‘Collections of Objects’: (C++)
(May help on Project 5)

•   A Game uses a bunch of ‘somethings’:
–    Several different classes
(robots, trees, clouds, castles, dogs, cats,...)
–    Each with different actions & abilities:
blink(), armsUp(), armsDown(), sleep(), walk(), run(),
–    May want to create/destroy objects as game progresses
–    How can we do that? first ask:

• How can we store them?
Hint: think about a ‘changing collection of objects’
as a ‘changing collection of struct variables’.
‘Collections of Objects’
(May help on Project 5)

•   Idea 0: Declare sets of individually named struct variables
for every possible object your program will ever need:
fishT      oneFish, twoFish, redFish, blueFish;
carT       carGo, carPet, carToon, carTell;
lokT       lokNess, iwazLok, shewasLok, swanLok;

All have complete ‘member’ variables that describe absolutely everything
that can change:
'name', 'isAlive', 'age', 'position', 'isHungry', isDry', 'energy'...

•   Idea 1: Fixed Arrays of struct variables: an array of fishT
objects, an array of carT, an array of lokT. Tedious,
inflexible, fixed; can’t easily create, destroy, swap, rearrange...
•   Idea 2: Dynamically-Alloc'd Arrays of struct variables;
make a pointer-to-fishT, a pointer-to-carT, a pointer-to-lokT,
then reserve memory for the array...
‘Collections of Objects’
(useful, but not included in Project 5)
•   Idea 3: Make a new struct to point to any ONE thing:
(optional; not needed for Project 5)

typedef struct holderT
{
int kindOf;   /* if kindOf==0, we are   EMPTY    */
fishT *pF;     /* if kindOf==1, point   to a fishT */
carT *pC;      /* if kindOf==2, point   to a carT */
lokT *pL;      /* if kindOf==3, point   to a lokT */
} holderT;

• The 'kindOf' member variable tells you which
pointer (pF, pC, pL, or none) to use.
All the other pointers are kept NULL.
‘Collections of Objects’
typedef struct holderT
{
int kindOf;   /* if   kind==0,   we are   EMPTY!       */
fishT *pF;    /* if   kind==1,   points   to a fishT   */
carT *pC;     /* if   kind==2,   points   to a carT    */
lokT *pL;     /* if   kind==3,   points   to a lokT    */
} holderT;

•   Idea 3: (cont'd):
•   Create an object? set the value for kindOf,
then malloc()an object for the selected pointer:
holderT myn;
...
myn.kindOf = 2; /* We will hold a carT object */
myn.pC = (carT *)malloc(1 * sizeof(carT));
myn.pF = NULL; myn.pL = NULL;

•   Destroy an object? use kindof to find its pointer;
call free() ...
•   Access an object? Lets try it.... assume a 'carT' object.
Write code to print its floating-point member 'x_vel' ...
Data Nesting
• Many forms of data are naturally nested: USE THIS!
– UniverseSolarSystemplanetcontinentcountrystate/
provincetownprecinctstreetbuildingroomchair
– Matrixrowelement
– Movieframescanlinepixelcolor
• Least restrictive, clearest data nesting tool: Structures
• Nested Structures: members are other structure types
– allows separate struct name for each nesting level:
houseT(yard,room,hall members),roomT(door,window,furnit. members)
furnitureT(desk,chair,bed members),deskT(drawer,leg,top,side...)

• Wonderful: Structures can use arrays as members
(fixed or dynamic alloc’d)
‘Collections of Objects’: (C++)
(May help on Project 5)
We humans tend to organize our world as collections of ‘objects’:

1.   We give names to classes of objects:
(or kinds of objects) birds, clouds, trees, people, triangles,
books, animals, buildings, chairs, tables, etc.

2.   Each kind of object has many variable parts;
name, address, salary, dept#, office#, SS#, supervisor, etc.

3.   An ‘object’ is just one named, countable, discrete object:

4.   Each class of object has many associated actions:
hire, fire, demote, promote, retire, re-assign, work
overtime, travel, vacation, training, move to new city, ...
‘Collections of Objects’: (C++)
(May help on Project 5)

Our best strategy in C:

Organize the entire program as a collection of ‘objects’;

1.   A ‘class of object’== data structure type we define and name
its member variables define each part of the object,

2.   One (data-structure-type) variable ==one countable object

3.   Each class of object has its own set of related functions
wagonInit(), wagonDraw(), wagonMove(), etc.
‘Collections of Objects’: (C++)

The strategy known as "Object-Oriented Programming"
(C++, Java, Modula, Smalltalk,...)
Organize the entire program as a collection of ‘objects’;

1.   A ‘class of object’== data structure type we define and name
its member variables define each part of the object,

2.   One (data-structure-type) variable ==one countable object

3.   Each class of object has its own set of member functions
wagon.Init(), wagon.Draw(), wagon.Move(), etc.
4.   In C++,
'class' == ( a struct + its 'member' functions )
‘Collections of Objects’: (C++)

Key idea of object oriented programming:

Object = data structure + all its related functions

Use nesting of classes to keep things simple:
cityT  streetT  houseT  roomT  chairT...

Writing cityT functions?
the number of chairs in each room!.
Misc. Lost Details
Congratulations!

• You now know all the essentials of C
• You're ready to learn a few key algorithms

• There are a few leftover details to clean up first:
"Hey! I can even point to myself!"
—a data structure
• Data structure members can be (almost) any type,
including
– all basic types: int, char, float, double
– all derived types: enum, arrays, pointers, structures
– even a pointer to our own kind of struct! if you're careful
but not array of our own kind of struct (do you know why?)

typedef struct employeeT/*****employee record *****/
{
char *name;       /* string variable         */
int IDnum;        /* employee ID #           */
float salary;     /* in dollars              */
char ssn[11];     /* xxx-xx-xxxx             */
struct employeeT *pBoss; /* immediate supervisor  */
struct employeeT *pPeon; /* team member           */
} employeeT;
Self-pointing is tricky...
• Data structure members can be (almost) any type,
including
– even a pointer to our own kind of struct!

SURPRISE! THIS SYNTAX DOESN’T WORK!

typedef struct employeeT    /*****employee record *****/
{
char *name;       /* string constant         */
int IDnum;        /* employee ID #           */
float salary;     /* in dollars              */
char ssn[11];     /* xxx-xx-xxxx             */
employeeT *pBoss; /* immediate supervisor    */
employeeT *pPeon; /* team member             */
} employeeT;
Self-pointing is tricky...
•   Instead, you must do this:
typedef struct employeeT   /*****employee record *****/
{
char *name;            /* string constant         */
int IDnum;             /* employee ID #           */
float salary;          /* in dollars              */
char ssn[11];          /* xxx-xx-xxxx             */
struct employeeT *pBoss; /* immediate supervisor */
struct employeeT *pPeon; /* team member           */
} employeeT;
?HUNH? WHAT HAPPENED HERE?
1.   actual datatype is ‘struct employeeT’, but
typedef renames datatype to ‘employeeT’
2.   These lines are compiled before typedef can do the renaming,
so they must use the actual datatype name struct   employee
scanf(): more of the story…
(CHAPTER 11-6 IN BOOK: look at 11-5 too!)
int scanf(“format string”, ptr1, ptr2, ptr3, …);
• Format String:
– Can set max # of chars for each data conversion:
– Can set separators (besides whitespace):

cnt = scanf(“%3i, %80s”,&my_int, msg);

• Return value: # of successful conversions (or –1 if
nothing at all matches)
• Destinations are ALL pointers/array names.
scanf(): more of the story…
(CHAPTER 11-6 IN BOOK: look at 11-5 too!)
int scanf(“format string”, ptr1, ptr2, ptr3, …);
• Format String:
– Can set max # of chars for each data conversion:
– Can set separators (besides whitespace):

cnt = scanf(“%3i, %80s”,&my_int, msg);

• Return value: # of successful conversions (or –1 if
nothing at all matches)
• Destinations are ALL pointers/array names.
scanf(): more of the story…
(CHAPTER 11-6 IN BOOK: look at 11-5 too!)
int scanf(“format string”, ptr1, ptr2, ptr3, …);
• Format String:
– Can set max # of chars for each data conversion:
– Can set separators (besides whitespace):

cnt = scanf(“%3i, %80s”,&my_int, msg);

• Return value: # of successful conversions (or –1 if
nothing at all matches)
• Destinations are ALL pointers/array names.
scanf(): more of the story…
(CHAPTER 11-6 IN BOOK: look at 11-5 too!)
int scanf(“format string”, ptr1, ptr2, ptr3, …);
• Format String:
– Can set max # of chars for each data conversion:
– Can set separators (besides whitespace):

cnt = scanf(“%3i, %80s”,&my_int, msg);

• Return value: # of successful conversions (or –1 if
nothing at all matches)
• Destinations are ALL pointers/array names.
scanf(): more of the story…
(CHAPTER 11-6 IN BOOK: look at 11-5 too!!)

int scanf(“format string”, ptr1, ptr2, ptr3, …);
• Format String:
– Can set max # of chars for each data conversion:
– Can set separators (besides whitespace):
– To read an entire line (up to 80 chars) of text as a
string, replace %80s with %80[^\n] (note: no ‘s’)

cnt = scanf(“%3i, %80[^\n]”,&my_int, msg);
“read a string, but don’t stop until
you read 80 chars or find a ‘\n’ ”
Format Strings: Can be Variable!

• So far, we’ve used only string constants:
scanf(“ %d”,&val);
printf(“Value is %d\n”,val);

• But we can use string variables too:
(recall: 'string' variable? use a pointer or array name)
char inMsg[10] = {“ %d”};
char outMsg[20] = {“Value is %d\n”};
...
scanf(inMsg,&val);
printf(outMsg,val);
(Recall) Literals
• Numerical literals in C are obvious:
int i;
float base_e;
i=3;
base_e = 2.718281828;

OR, more compactly:
int i = 3;
float base_e = 2.718281828;

These literals set the values for i, base_e,
and are not L-values—they do not have an address.
pV = &3;     pF = &2.71828;        3 = &pF;
ERROR!!
String Literals?
• String Literals in C are a little strange:
they ARE L-values, they DO have address:
char *pMsg;
...                                     String literal
pMsg = “Are we having fun yet?”;
• OR, more compactly:
char *pMsg = “Are we having fun yet?”;
• Pointer pMsg gets the address of a string literal.
Literal's chars are in 'locked' memory--‘const’.
ERROR if you try to change its contents!

strcpy(“Real Soon now!”,pSrc);       ERROR!!
String Constants
Reminder: Arrays aren’t movable!
• We can move a pointer pMsg to a string literal’s address:
char *pMsg;
pMsg = “Are we having fun yet?”;        // OK!

• And we can initialize an array msg by copying a string literal:
all chars

char msg[20] = {“Are we having fun yet?”}; // OK!

• But we can’t move an array name msg to that location:
char msg[20];
msg = “Not this way, no!”;             // ERROR!
Build a String: sprintf()
int sprintf( pStr, format_string, arg0, arg1, …)
• Think “string printf”– it constructs a formatted, printable string
of chars in memory, starting at location pStr.

• Arguments:
pStr char. pointer to showing where to write string
format_string (same as used in printf)
arg0, arg1, … list of values used in format string

• Return value:
number of non-null chars written to pStr

WARNING!! Reserve a block of memory at pStr first!
• Uses Char Pointer arguments and return types:
(pass-by-reference)
• YOU must ensure enough memory was reserved for
all operations of all string.h functions!
MAJOR source of subtle bugs!
• All have form str(n)xxx (dest, src, n), and include:
length strlen,      copy strcpy,
compare strcmp, concatenate strcat,
find char strchr, find string strstr.

• Other, more obscure string.h functions:
strerror(), strpbrk(), strtok(),
strcspn(), strspn(), …
Jargon: Buffer
• Buffer: temporary storage for a data sequence
• A pointer is not a buffer until
it points to a reserved block of memory
– Reserved by dynamic allocation (malloc,free) or
– Reserved by a declared array (still in scope, or static)

• CAUTION: never ‘over-run’ a buffer;
make sure all string lengths <= buffer length

• HELPFUL: All string.h functions have an ‘n’
version: strncpy, strncmp, strncat, strnchr …
operates on only the first ‘n’ characters
Subtlety of strncpy, strncat
char *strncpy(char* dest, char* src, int n);
– Always copies ‘n’ chars to ‘dest’. Of these, it…
– Copies ‘src’ chars until null ‘\0’ char found, then
– Copies additional ‘null’ chars after that.
– CAREFUL! If ‘src’ longer than n, NO ‘null’ char!!

char *strncat(char* dest, char* src, int n);
– Appends no more than ‘n’ chars from src onto dest
– CAREFUL! If ‘src’ longer than ‘n’, NO null char!!
Other useful string.h functions

int strncmp(char* str1, char* str2, int n);
– Compares first ‘n’ characters of strings 1 & 2;
– Returns the DIFFERENCES; 0 == perfect match!

char* strchr(char* str, char ch);
– Searches string ‘str’ for the 1st char ‘ch’ it finds,
– Returns pointer to the char it found, or NULL

char* strstr(char* str, char ch);
– Searches string ‘str1’ for the 1st string ‘str2’ it finds,
– Returns pointer to the string it found, or NULL.
Finish up:

• Worthwhile topics:
– Search, Sort Chapter 8-5
– Intro to C++

• Skipped so far:
–   Chapter 13-1,2 Binary files,
–   Chapters 13-4 fgets/gets+sscanf, fputs/puts+sprintf
–   Chap 15: Bitwise operators, bit-shift
–   Appendix G: pre-proc directives #include
–   Appendix I: command-line arguments
–   Appendix J; Function pointers

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 1 posted: 7/28/2012 language: pages: 32