CS2 - PowerPoint PPT Presentation

1 / 80
About This Presentation
Title:

CS2

Description:

Then Why C? The language is ubiquitous. C is 'fast' relative to ... DOS/Windows users may also need to #include conio.h . The basic printf command is: ... – PowerPoint PPT presentation

Number of Views:61
Avg rating:3.0/5.0
Slides: 81
Provided by: davidd1
Category:
Tags: cs2 | expensive | is | so | why | windows

less

Transcript and Presenter's Notes

Title: CS2


1
CS2
  • Introduction to
  • Object Oriented Programming
  • C
  • (Lets do it all again in C)

2
  • CS 1322 Official Final Exam Schedule
  • Section B (1200-145 lecture)
  • Lecturer Bill Leahy
  • Final Exam
  • Date August 1, 2001
  • Time 250-540
  • Location Physics L3 (Normal class meeting
    location)
  • Bring pencils, eraser. No books, notes,
    calculators, etc.
  • No one will be admitted after 305 p.m.

3
Agenda
  • Motivation
  • C history
  • C compilation (unix)
  • C syntax
  • variables
  • procedures
  • simple examples
  • Structs, typedefs
  • A hint at pointers

Caution - it will be hard to distinguish in this
discussion between what the C language allows you
to do, and what good practice suggests that you
do...
4
Motivation
  • Future CS courses will require you to write in C
  • 2130, 2200
  • 3000 level, 4000 level, 6000 level, 8000 level...
  • C is so powerful and so old that no matter what
    your major you may run into tools, equipment,
    techniques that require writing/modifying/understa
    nding some C code
  • Many people do not consider C to be a high level
    language at all. They consider it to be an easier
    way to write assembly code. Thus in one sense it
    can do anything!

5
Motivation
  • Different computer languages are not like
    different flavors of ice cream.
  • They don't just do the same thing with different
    syntax
  • Some languages like Scheme and Lisp attempt to
    completely divorce the programmer of any
    knowledge of the actual hardware running the
    program.
  • Other languages are more closely tied to the
    hardware.
  • C is very close to the hardware and some programs
    require knowledge of how the computer actually
    works internally.

6
Motivation
  • When you see some of the challenges of C, you
    might appreciate more how much Java really does
    for you
  • avoiding pointer badness
  • managing memory
  • compile time type checking
  • second generation string management (toString())

7
C
8
Then Why C?
The language is ubiquitous. C is fast relative
to interpreted languages. C is "fast" compared
with any language that has a lot of built-in
overhead to keep you out of trouble Its
available on almost every platform, and with
recent standards, its become possible to write
(fairly) portable code. In fact, C is the lowest
level language where some portability can be
assured across architectures (platforms). I.e.
its the lowest level high level language
9
History (Short Version)
  • C was originally created as a language with which
    one could write operating systems. (like Unix).
  • It was created in the 70's
  • Computers were much slower.
  • Computers were much more expensive
  • Memory was incredibly expensive (gt 0.01/bit!)
  • Few engineers/programmers could type fast
  • Serious coding was done in assembler
  • Writing operating system code in assembler while
    perhaps not that much fun was necessary

10
Core Memory
Up until the mid-1970s, computer memory was
usually composed on small magnetic rings
(toroids) that would use polarity (North/South)
to represent a bit. Wires run through the rings
would sense or change the polarity of a ring. The
rings were known as magnetic cores.
11
Core Dumps
  • Core memory was used as high speed random access
    memory. (Where we use chips today.)
  • It was very expensive (gtgt 0.01/bit in 1968).
  • (1 Mb 8 Mbits 80,000.00)
  • The term "Core" was used as opposed to "Disk"
    memory.
  • Languages such as Fortran and C did not do
    extensive error checking so when something went
    wrong the machines would dump (print) the
    contents of the RAM to allow the programmer to
    find out where the error occurred.
  • This became known as a core dump. This technique
    is still used although the cores are gone!

12
Versions of C
In 1978, Dennis Ritchie and Brian Kernighan
published a book describing the C language.
It became the best selling computer book ever
(500,000 copies sold). The syntax style of the
original edition was somewhat different than
subsequent (ANSI) versions. Old unix hackers
sometimes use KR C style, and compilers still
recognize it.
Buy, borrow or steal but own this book.
13
Historical Note
  • If you download this presentation you will find
    an additional 13 or so slides about the history
    of C.
  • To view them you will need to unhide them!

14
What Is That Which Is C?
Some folks make a big fuss over ANSI C versus
KR C versus (heh) MFC. Countless debates over
syntax decay into a discussion of which version
of C one should use. This can be intimidating.
15
Dont Believe the Hype
Dont be intimidated by grizzled old C hackers.
Lets arm ourselves with a knowledge of the
history of C. That way, when youre in a debate
over syntax, you wont get pushed around by the C
bullies. Also, this history of C explains some
of its features.
16
Prehistory
In the 1960s, several monopolies teamed up to
create the greatest operating system that never
was. General Electric, MIT, and Bell Labs
collaborated on the Multics Project--a fast,
efficient operating system. The trouble was,
Multics was too big. It didnt fit well on any
existing hardware. (Just like IBMs
OS/360--bloat, bloat, bloat.) Multics solved
many engineering problems in software, but did
too many things.
With no realistic platforms, the monopolists
retreated from the project.
Learn more http//cm.bell-labs.com/cm
/cs/who/dmr/chist.html
17
The Playas.
Two researchers are ATT decided to use some of
the technologies developed in the Multics project
in a new OS (all because they wanted to run a
Space Travel game, actually). They called it
Unix as a parody of Multics, since it was much
simpler, and light weight.
Ken Thompson
Well talk about this criminal shortly ...
Dennis Ritchie
18
Back in the Day
Thompson and Ritchie were porting the space game
to a PDP-7, a computer made by Digital Equipment
Corporation (DEC). As the successor to the
PDP-5, it was Digitals first mass-storage
machine ever. 120 such machines were made and
sold.
19
Pop Quiz!
  • Q What does PDP stand for?
  • A Programmed Data Processor

20
The Nature of Computing
  • Back in those days
  • memory was very expensive
  • programs had to be small and fast
  • serious coding was done in assembler
  • writing operating system code in assembler while
    perhaps not that much fun was necessary

21
B An Improved BCPL
Meanwhile, back in the lab... Ritchie and
Thompson found they needed a new language to
quickly implement the UNIX operating system.
Thompson experimented with Fortran, and then
created B by modifying an existing language
called BCPL (created by London and Cambridge
Univ., UK), in order to fit onto the PDP-7s 8K
word memory size.
How B differed from BCPL
No nested procedures Fewer looping
constructs Typeless language (machine words
only) Created the and -- operators NOTE
Many people incorrectly believe these operators
were added to C because the PDP-11 had auto
increment / decrement addressing modes. Not so!
22
Pop Quiz
  • Q What does BCPL stand for?
  • A Basic Computer Programming Language

23
On to C
The typeless B language proved ineffective for
implementing Unix. It worked on the PDP-7, but
was slow. Then, in 1970, Digital released the
PDP-11, which had processor support for data
types of various size.
Since B had no way to express data type sizes,
they decided to switch to the new PDP-11 and
created a new version of B. This became known as
C.
The PDP-11 featured a single bi-directional async
bus. The UNIBUS allowed devices to send/receive
without intermediate buffering. It was the first
computer to interface processor, memory and
peripherals all on one bus. It became the most
successful minicomputer ever.
Sadly, many years later, Compaq purchased
Digital.
24
Towards ANSI C
By the early 1980s, C became very widely used.
The PC makers soon realized Cs advantages over
BASIC, and provided implementations for the PC
market.
Microsoft made a version of C for the PC that
introduced new keywords, (e.g., far and near) to
address pointers on the irregular x86
architecture.
Other implementations made variations as well.
The C language began to change under corporate
influences. It became clear that a standard was
needed, just like every other language had.
25
ANSI
In 1983, the American National Standards
Institute created a workgroup (called X3J11) to
study C. They looked for common features and
attributes in various C implementations. E.g.,
Microsofts far and near keywords did not make
the cut. The end result was a UNIX-centric
version. In December, 1989, ANSI formally
adopted Standard X3.159-1989, or ANSI-C
Some people call this C89, but only if theyre on
a first name basis with the standard.
26
ISO
Because C had become an international language,
the International Standards Organization (ISO)
then examined C through committee ISO/IEC
JTC1/SC22/WG14(C), called Working Group 14,
chaired by P.J. Plauger. They made minor
editorial changes, and adopted WG14 as ISO/IEC
98991990.
Messr. Plauger editor of the C/C Users Journal,
and purveyor of standards
The trouble is, the ISO group omitted the helpful
Rationale section of the ANSI standard.
Read the Rationale document at
ftp//ftp.uu.net/doc/standards/ansi/X3.159-1989
27
... then ANSI again ...
Since the ISO standard was slightly different,
the ANSI then adopted the ISO version (or more
correctly, re-adopted what was mostly their 1989
ANSI-C standard), which did not include the
Rationale document. The ANSI C standard is also
a European standard (CEN 29899), and X/Open
standard, a NIST Federal Information Processing
Standard (FIPS 160, March 1991, rev. Aug. 24,
1992).
So, what is ANSI C? The ISO version without the
rationale document? Or the 1989 version that
included this document?
28
But Wait! History Continues
  • Work on C continues...
  • In 1994, the ISO group WG14 produced Amendment 1,
    which had features for
  • library support for foreign characters
  • multibyte characters and wide characters
  • new standard header files
  • (iso646.h, wctype.h, wchar.h)
  • tokens and macros for punctuation
  • in other languages
  • printf/scanf functions

29
Historical Influences on C
The fact that UNIX was first implemented in
assembly (on the PDP-7 and PDP-11, and later
rewritten in C when a compiler was available),
had several influences on Cs design
30
... MORE?
In 1994, the ISO WG14 also produced a Technical
Corrigendum 1 to ISO C, as a bug fix against
the early standard. This resolved some 35
contradictions in the standard, which took some 6
years to make. (See? cs1312 program nfo files
are not bad by comparison.) And they are still
at it....
We generally refer to modern C as ANSI-C,
though it should be called ISO-C
So, the next time a newsgroup bully starts off on
KR vs. ANSI C, ask if he means ANSI adopted
ISO C, the FIPS standard, or the X3J11 version
without the Corrigendum. Theyre very much the
same, but the intimidation factor will be
tremendous.
31
What Early C Did Not Do
Runtime libraries. Other languages create
runtime code for memory allocation, array bounds
testing, range checks, dynamic memory use. C
does not. There are libraries you can use to
help with these chores, but you have to use them
correctly. Preprocessing/Macro
Formatting. Early C lacked a way to make String
replacements in code, source file inclusion
(pioneered in BCPL). Most C compilers now come
with a pre-processor that helps format code.
32
Standardization
  • C is now governed by various standards (e.g.
    ANSI)
  • Standardization committees were operating when a
    lot of code was in use.
  • Clear choice Break existing code or allow
    differences to live on. Note Many of these
    differences were caused by implementations on
    different machines.
  • The choice was Standardization or speed?
  • Speed!!!

33
Questions?
34
Work Flow of a C Compiler
Source Code
Source Code
Source Code
Assembler
KEY
Preprocessor
Object Code
Object Code
Phase of compilation (specific program or
subprogram)
Object Code
other stuff
Compiler
Link Editor
Output (to file or memory)
Assembly Code
Executable Code
35
Source Code
C source code is written in text files. By
convention, these files are given an appropriate
name, and a .c extension.
Just like Java... ...starts with main
The contents of a file called hello.c More on
the syntax later
All modules in C are called functions. If you
call them methods...
36
Compilation
Warning
After a successful compile you will find a file
named hello in your directory Run it by simply
typing hello
If this fails, type ./hello
37
File Extensions (gcc)
There are many compilation options. But well
just focus on files that have Source (.c files)
-- the actual code Headers (.h files) -- kinda
like an interface,
but not exactly
38
Contrasting C with Java
  • On the surface, much simpler to deal with
  • Actually, closer to pseudocode
  • Simplicity comes at a high price
  • freedom encourages lack of structure
  • not enough compile-time validation
  • cross-platform portability uncertain
  • size of ints and floats
  • Closer to the bare metal
  • micro-managing I/O operations
  • memory management and pointers
  • little run-time error checking
  • C has no explicit String type

39
Beyond Hello World
  • include ltstdio.hgt
  • / Calculate temp conversion table /
  • int main (void)
  • int fahr, celc
  • int min, max, step
  • min -40
  • max 100
  • step 5
  • fahr min
  • while (fahr lt max)
  • celc 5 (fahr-32)/9
  • printf ("d\td\n", fahr, celc)
  • fahr fahr step
  • return 0

40
Beyond Hello World
  • include ltstdio.hgt
  • / Calculate temp conversion table /
  • int main (void)
  • int fahr, celc
  • int min, max, step
  • min -40
  • max 100
  • step 5
  • fahr min
  • while (fahr lt max)
  • celc 5 (fahr-32)/9
  • printf ("d\td\n", fahr, celc)
  • fahr fahr step
  • return 0

We must declare all local variables at the top of
the procedure.
Contrast this with Java
41
Beyond Hello World
  • include ltstdio.hgt
  • / Calculate temp conversion table /
  • int main (void)
  • int fahr, celc
  • int min, max, step
  • min -40
  • max 100
  • step 5
  • fahr min
  • while (fahr lt max)
  • celc 5 (fahr-32)/9
  • printf ("d\td\n", fahr, celc)
  • fahr fahr step

42
Beyond Hello World
Lets talk about these details... in detail....
  • include ltstdio.hgt
  • / Calculate temp conversion table /
  • int main (void)
  • int fahr, celc
  • int min, max, step
  • min -40
  • max 100
  • step 5
  • fahr min
  • while (fahr lt max)
  • celc 5 (fahr-32)/9
  • printf ("d\td\n", fahr, celc)
  • fahr fahr step

We cast the arguments to a void type. Theres a
way to get command line arguments, just like
String args in Java, but it uses pointers to
pointers. (We cover this later.)
Integer truncation occurs here, just like in
Java.
43
Two Flavors of Header Files
  • Local headers
  • referred to with includexxx.h
  • when used properly, function as the public
    section of your file for use by others
  • main program includes it to verify compliance
  • also allows main program components to occur in
    any order
  • includes constant definitions
  • System headers
  • referred to with include ltxxx.hgt
  • provide access to all system facilities
  • find specifics in standard library references

include ltstdio.hgt include ltconio.hgt include
another_header.h
include local_header.h include
ltsystem_header.hgt
44
Basic Printing
If you want to do any printing in your C program,
youll likely have to include the stdio.h header
file, or standard Input/Output header
include ltstdio.hgt
DOS/Windows users may also need to include
ltconio.hgt. The basic printf command is
int num 5 printf (The number is d, num)
Think of this as a String literal, like you saw
in Java (Its actually a const char, a pointer
construct more later.)
d means substitute the number (digits) into
the string
45
Basic Printing
If you want to do any printing in your C program,
youll likely have to include the stdio.h header
file, or standard Input/Output header
include ltstdio.hgt
DOS/Windows users may also need to include
ltconio.hgt. The basic printf command is
int num 5 printf (The number is d, num)
The number you want printed must appear here. If
it does not, C will make up something, using
random garbage off the stack.
46
Basic Printing
If you want to do any printing in your C program,
youll likely have to include the stdio.h header
file, or standard Input/Output header
include ltstdio.hgt
DOS/Windows users may also need to include
ltconio.hgt. The basic printf command is
int num 5 printf (The number is d\n, num)
The usual control characters you learned in Java
still work. The \n is a new line. The \t is a
tab, etc.
47
Pop Quiz
This is a very common mistake. Your program will
compile and run. It will just give the
wrong answer, some of the time.
Q
Whats 2 2 in C?
int answer 2 2 printf (Two plus two
d\n)
48
Data Types
  • ANSI C has five atomic data types, and many,
    many modifications to the atomic types.

Thus int x unsigned int y
Not every permutation of type and modification is
found in ANSI C.
49
Variables
Variables in C are similar to variables in Java,
except a) they do not (as in Java) have to be
part of a class b) under C rules, local
variables can be made to persist after procedures
are terminated but by default, they are
automatic variables that are destroyed after
the method returns.
Java
C
class Num int x public static void main
(String arg )
int x int main (void)
50
Variables
Local variables work the same as in Java, except
that you can make one retain value with the
keyword static. Note that static in Java
works in a somewhat similar manner.
void do_something(void) int x x x
1
void do_something(void) static int x
x x 1
Variable x is local only to this procedure
value is retained on global heap not lost
after procedure ends
Variable x is local only to this procedure
value is lost after procedure ends.
51
Control Statements
C has no boolean type, unlike Java. So, it
instead uses a number, 0, to be false. ANY
other number is true.
int x 1 while (x) / creates infinite
loop, unless x ever 0 /
52
Control Statements
Most C programs take advantage of the fact that
zero is false, and anything else is true
int count 10 while (count gt 0) printf
(Count d\n, count) count count - 1
BECOMES
A No. Trace it.
int count 10 while (count--) printf
(Count d\n, count)
Q Are these the same?
THIS IS NOT CONSIDERED GOOD STYLE!
53
Control Statements and Assignment
Ever do this in Java? int x
getNumber() if ( x 10 ) //
etc. See the error? It should be , not
. Thankfully, the java compiler is your friend,
and gives you a friendly error.
54
What?
Why does this work in C? Whenever C assigns a
number, it leaves that value on the stack.
int x 13 The number 13 is now on the top
o the stack. Since ANY number other than zero
is true, whats left on the stack is evaluated
with int x get_number() if
(x 34) / some code /
Java actually works the same way!
55
One way to fix problem
So, int x get_number() if (x 34)
/ some code / is always true,
since 34 is left on the stack. C will not stop
you from this error. Your code will compile and
run.
Hint By reversing the arguments, you would give
you the compilation error you probably wanted to
get!
int x get_number() if (34 x) / some
code /
56
Procedures
As youve by now guessed, C supports procedures
as well. Unlike Java, they are not qualified as
public, private or protected. In C, everything
is public in a sense.
include ltstdio.hgt do_something(char x)
printf (c\n, x) int main (void)
do_something(67)
implicit cast from int to char bad style
implicit values returned bad style
Note By specifying warnings these "potential"
errors are caught.
57
gcc -Wall -ansi -pedantic -o2 -d hello.cNote
Without -o hellooutput file is a.out
  • getting serious...

58
Procedures
Remember Cs origins as a step above assembly?
To make compiler design simple, you must declare
all local variables at the start of a procedure.
void calculate(int r) int area area PI
r r int diameter r 2
ERROR!
Providing a default value with declaration will
not cause an error, however.
void calculate(int r) int area int
diameter area PI r r diameter r
2
59
include ltstdio.hgt int convert_fahr_to_celc(int
f) return 5 (f-32)/9 int main
(void) int fahr, celc int min, max, step
min -40 max 100 step 5
fahr min while (fahr lt max) celc
convert_fahr_to_celc(fahr) printf
("d\td\n", fahr, celc) fahr fahr
step
Be sure all procedures return the type of
values you promised. Whats missing here?
60
include ltstdio.hgt int convert_fahr_to_celc(int
f) return 5 (f-32)/9 int main
(void) int fahr, celc int min, max, step
min -40 max 100 step 5
fahr min while (fahr lt max) celc
convert_fahr_to_celc(fahr) printf
("d\td\n", fahr, celc) fahr fahr
step
The main procedure, under ANSI-C, must return a
number indicating its exit status. (Zero usually
means success). Else, we might get a warning, but
usually not.
return 0
61
include ltstdio.hgt int convert_fahr_to_celc(int
f) return 5 (f-32)/9 int main
(void) int fahr, celc int min, max, step
min -40 max 100 step 5
fahr min while (fahr lt max) celc
convert_fahr_to_celc(fahr) printf
("d\td\n", fahr, celc) fahr fahr
step
Also, take on faith that you SHOULD (for now)
place all other procedures above main(), else you
might get a warning. Theres a way using
prototypes to avoid this (not covered)
return 0
62
Questions?
63
Put Some Structure in Your Life
  • C uses a struct to group one or more variables
    into a single unit
  • Equivalent to a record in Pascal and Pseudocode
  • Equivalent to a class with no methods (the
    horror...) in Java
  • Equivalent to structures in Scheme!
  • Example
  • struct point
  • int x
  • int y

64
Structures
  • The preceding example was a declaration, that is,
    it essentially creates a new type.
  • In this case we included the word point which
    is known as a structure tag
  • Now we can say

struct point pt1 struct point pt2 pt1.x
5 pt1.y 7 pt2 pt1
65
Structures
  • We could even say
  • struct
  • int x
  • int y
  • pt3, pt4
  • Note that while
  • pt2 pt1
  • pt3 pt4
  • both work
  • pt3 pt2
  • does not!

struct point int x int y struct
point pt1 struct point pt2 pt1.x 5 pt1.y
7 pt2 pt1
66
Structures
  • Structures
  • can be copied or assigned
  • can have their address taken using (more next
    time)
  • can be passed to and returned from functions
  • struct point doublePoint(struct point in)
  • struct point temp
  • temp.x 2 in.x
  • temp.y 2 in.y
  • return temp
  • may be initialized
  • struct point maxpt 320, 200
  • can be used in arrays (arrays of structs)

67
Self-Referential Structures
  • Self-referential simply means a structure that
    contains a reference or pointer to a structure of
    its own type.
  • struct lnode
  • int data
  • struct lnode next
  • More on pointers next time...

68
Roll Your Own!
  • For readability and convenience it would be nice
    to be able to make up synonyms for existing types
  • The typedef keyword provides this facility
  • Example
  • typedef int Length
  • Now saying
  • Length x, y, z
  • is the same as saying
  • int x, y, z

69
Putting it all together
  • typedef struct point
  • int x
  • int y
  • point_type
  • Or even
  • typedef struct point
  • int x
  • int y
  • point

C keeps these names in separate spaces
So now we can say point p1, p2
70
Watch closely!!!
  • typedef struct lnode
  • point data / Nested structure /
  • struct lnode next
  • lnode
  • lnode head

71
Another common way!!!
  • typedef struct lnode_tag
  • point data / Nested structure /
  • struct lnode_tag next
  • lnode
  • lnode head

72
Structs One More Time
Confused? This might help. The syntax of a
typedef is as follows typedef lttypegt
lthandlegt Thus typedef int myType If the
type that we typedef is a struct, we
get typedef struct ... myTemp
73
Questions?
74
(No Transcript)
75
Bits, Bytes and Words
  • A bit is a binary digit which can have a value of
    0 or 1
  • A byte today is normally considered to be 8 bits
    but was originally designated as the smallest
    addressable unit of memory
  • Thus one could instruct the computer to store or
    retrieve a given byte but not a given bit.
  • Bytes may be grouped into words (e.g. 4 bytes)
  • (plus all kinds of zany combinations thereof like
    half-words, double words, etc.)
  • So words are addressed in multiples of 4
  • Since the bytes are addressed by one.

76
Conceptual Memory
  • Each memory cell thus has two associated numbers
  • Its address
  • Its contents
  • When using any symbolic language we can also
    associate a symbol or identifier
  • Example
  • Memory Address Contents Symbol
  • or Identifier
  • 2000 7 someInt

We write int someInt someInt 7
77
Conceptual Memory
Technically this only exists up through
compilation.
  • Memory Address Contents Symbol
  • or Identifier
  • 2000 7 someInt

78
Strictly Speaking
  • The computer has no idea what were actually
    doing (exception see HAL in 2001)
  • So a given memory location such as a byte only
    has a limited number of possible values
  • Byte 0 - 255 (00 - FF16)
  • It is the programmer using a programming language
    that can assign this byte a meaning
  • Unsigned numbers from 0 to 255
  • Signed numbers from -128 to 127
  • Characters from a typical encoding such as ASCII
    where for example the letter A is represented
    by the number 65
  • Thus we could also store in memory the address of
    any memory location. This is known as a pointer.

79
More Memory
  • Notes
  • The SYMB column isnt actually stored in memory.
  • In fact, neither is the column marked ADDR!
  • Assume that we are showing words (32 bits)
  • Assume ints take a word

2000
7
ix
2004
42
iy
2008
-17
iz
80
Initializing It
  • The code
  • int ix 7

2000
7
ix
Note Where the actual values get stored depends
on several factors. Since we deal with the
symbols, we dont worry about this most of the
time.
2004
2008
81
Assigning to it
  • The code
  • int ix 7
  • int iy, iz

2000
7
ix
2004
?
iy
2008
?
iz
82
Assigning to it
  • The code
  • int ix 7
  • int iy, iz
  • iy 42

2000
7
ix
2004
42
iy
2008
?
iz
83
Assigning to it
  • The code
  • int ix 7
  • int iy, iz
  • iy 42
  • iz iy - 59

2000
7
ix
2004
42
iy
2008
-17
iz
84
A Pointer at last!
  • The code
  • int pint

1000
pint
2000
7
ix
Possible Points of Confusion 1. The pointer is
named pint not pint 2. It is not necessarily the
size of an int rather it is pointing to an int.
Important in a minute.
2004
42
iy
2008
-17
iz
Can also be written as... int pint
85
Make it point!
  • The code
  • int pint
  • pint ix

1000
2000
pint
2000
7
ix
2004
42
iy
2008
-17
iz
86
Dereferencing
  • The code
  • int pint
  • pint ix
  • pint 8

1000
2000
pint
2000
8
ix
Syntax Note int pint Means that when pint
is dereferenced it will be pointing to an int
2004
42
iy
2008
-17
iz
87
Dereferencing
  • The code
  • int pint
  • pint ix
  • pint 8
  • pint iy

1000
2000
pint
2000
50
ix
2004
42
iy
2008
-17
iz
88
Fasten Your Seat Belt!
was 2000
  • The code
  • int pint
  • pint ix
  • pint 8
  • pint iy
  • pint 1

1000
????
pint
2000
50
ix
2004
42
iy
2008
-17
iz
89
Fasten Your Seat Belt!
  • The code
  • int pint
  • pint ix
  • pint 8
  • pint iy
  • pint 1

1000
2004
pint
2000
50
ix
2004
42
iy
Why do they call it notorious pointer arithmetic?
2008
-17
iz
90
Pop Quiz
  • int x, y
  • int px x
  • int py y
  • x 7
  • py 5
  • py px
  • px px y py
  • printf(d d\n, px, py)
  • What prints?

91
Pop Quiz
  • int x, y
  • int px x
  • int py y
  • x 7
  • py 5
  • py px
  • px px y py
  • printf(d d\n, px, py)
  • 19 19

92
Hilarious Implications
  • Remember we only have in parameters in C
  • So we can fake it!
  • Lets say we want to write a function (procedure)
    to swap two numbers
  • void swap(int a, int b)
  • int t
  • t a
  • a b
  • b t
  • Doesnt work since parameters are in
  • Pass by Value

93
But we can fool the computer!
  • void swap(int a, int b)
  • int t
  • t a
  • a b
  • b t
  • Called like this
  • int x, y
  • x 3
  • y 4
  • swap(x, y)

Notice 1. We didnt actually create any pointer
variables in our calling sequence. 2. We dont
change a and b inside of swap just what they are
pointing to...
94
Pop Quiz
  • include ltstdio.hgt
  • void print_num (int x)
  • printf("Number d\n", x)
  • int main (void)
  • int a 3
  • int b
  • b a
  • print_num(??)
  • return 0

Which one goes here to print 3? b b b
95
Pop Answer
  • include ltstdio.hgt
  • void print_num (int x)
  • printf("Number d\n", x)
  • int main (void)
  • int a 3
  • int b
  • b a
  • print_num(b)
  • return 0

96
Pop Quiz
  • include ltstdio.hgt
  • void print_num (int x)
  • printf("Number d\n", x)
  • int main (void)
  • int a 3
  • int b
  • b a
  • print_num(b)
  • return 0

b Pointer to an int b What b is pointing
at b Address where b is stored
97
Questions?
98
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com