Title: CS 192
1CS 192
- Lecture 12
- Winter 2003
- December 31, 2003 - January 1, 2004
- Dr. Shafay Shamail
2Pointer
- Points to an item
- Holds the memory address of the item
- Has its own memory storage
- Occupies space in memory
- Hence can itself be accessed too
- Allows C/C to support dynamic memory allocation
- If x contains the address of y, x is said to
point to y - Pointer variables are declared as
- type var-name
- e.g. int p pointer p contains the memory
address of an int variable - float fl points to a float variable
3Assumptions
- characters are one byte in length
- integers are four bytes long
- floats are four bytes long
- doubles are eight bytes long
4Pointer Operators
address of value at address
a address of variable a p contents of
location pointed to by variable p
5Pointer Operators
- (address operator)
- a unary operator that returns the memory address
of its operand. - int balance 350
- int balptr
- balptr balance
- This address is the location of the variable in
memory, it has nothing to do with the value of
balance.
6Pointer Operators
- (indirection operator)
- Is the complement of .
- It is a unary operator that returns the value of
variable located at address specified by its
operand. - int balance 350
- int balptr
- balptr balance
- int value
- value balptr
- // what does value contain?
7Pointers
- int a1, b2, p
- Picture in memory at this point
- pa //p is assigned the address of a
- bp //b is assigned the value pointed to by p
- As p points to a, the statement bp is
equivalent to ba
8Pointer Operators
int main() int balance int balptr int
value balance 3200 balptr balance
value balptr cout ltlt "balance is " ltlt
value ltlt '\n' cout ltlt "Memory address where
balance is stored is ltlt balptr ltlt
endl return 0
9Output
- balance is 3200
- Memory address where balance is stored is
0012FF7C - (Note memory address may be different when you
run it on your machine)
10Base Type
- value balptr
- The compiler transfers the proper number of bytes
according to base type. - int p
- double f
- // ...
- p f // ERROR
11Assigning Values Through a Pointer
int p int x 12 px cout ltlt x ltlt
endl //Assign a value to the location pointed
to by p p 101 cout ltlt x ltlt endl //what is
value of x? cout ltlt p ltlt endl cout ltlt p ltlt
endl cout ltlt x ltlt endl
12Assigning values through a pointer
12 101 101 0012FF78 0012FF78
13Assigning Values Through a Pointer
(p) //increment value to the location pointed
to by p int main() int p, num p
num p 454 cout ltlt num ltlt ' '
(p) / parentheses are necessary because
operator has lower precedence than operator
/ cout ltlt num ltlt ' ' (p) - - cout ltlt
num ltlt '\n' return 0 //Output?
14Assigning Values Through a Pointer
//Output is 454 455 454
15Pointer Arithmetic
- There are only four arithmetic operators that can
be used on pointers , --, , - - Let p1 be an integer pointer which contains the
address 5000 - p1 // now p1 will be 5004
- Each time p1 is incremented, it shall point to
the next integer. - p1-- will cause p1 to be 4996 if initially it
was 5000.
16Pointer Arithmetic
- Let p1 be a char pointer which contains the
address 4000 - p1 // now p1 will be 4001
- Each time p1 is incremented, it shall point to
the next character. - p1-- will cause p1 to be 3999 if initially it
was 4000. - Pointer of type other than char shall increase or
decrease by length of base type.
17Pointer Arithmetic
- You cannot add two pointers
- You can subtract two pointers (if they are of
same base type). - Other than
- addition or subtraction of a pointer and an
integer, OR - csubtraction of two pointers,
- no other arithmetic operations can be performed
on pointers. - You cannot add or subtract float or double values.
18Pointer Arithmetic
int main() int iptr, a //which is pointer
to int? which is int? double fptr, b int
x a 10 b 20 iptr a fptr
b for ( x 0 x lt 10 x) cout
ltlt iptrx ltlt " " ltlt fptrx ltlt '\n'
return 0
19Pointers and Arrays
- In C, there is a close relationship between
pointers and arrays. - Two examples
20Pointers and Arrays
int main() int iptr int iarray4 5,
6, 7, 8 iptr iarray cout ltlt iptr ltlt "
" ltlt iarray ltlt \n cout ltlt iptr0 ltlt "
" ltlt iarray0 ltlt \n cout ltlt (iptr1)
ltlt " " ltlt iarray1 ltlt\n return 0
//Output?
21Pointers and Arrays
Output is 0012FF6C 0012FF6C 5 5 6 6
22Pointers and Arrays
int b 10, 20, 30, 40, 50, 60, 70, 80,
90, 100 int bptr b // set bPtr to
point to array b int b2ptr b5 / set
b2Ptr to point to sixth element of array
b / cout ltlt "b" ltlt 5 ltlt " " ltlt b5 ltlt
endl cout ltlt "b2ptr " ltlt b2ptr ltlt endl
cout ltlt "(b2ptr - bptr) " ltlt (b2ptr - bptr) ltlt
endl
23Pointers and Arrays
int b 10, 20, 30, 40, 50, 60, 70, 80,
90, 100 int bptr b // set bPtr to
point to array b int b2ptr b5 / set
b2Ptr to point to sixth element of array
b / cout ltlt "b" ltlt 5 ltlt " " ltlt b5 ltlt
endl cout ltlt "b2ptr " ltlt b2ptr ltlt endl
cout ltlt "(b2ptr - bptr) " ltlt (b2ptr - bptr) ltlt
endl Output is b5 60 b2ptr
60 (b2ptr - bptr) 5
24Pointers and Arrays
int i145,6,7,8 int i241,2,3,4 i2i1
//NOT ALLOWED Why? /name of array is a constant
that points to beginning of array/ char
str1i am a string char str2i am a
string str1str2 //WRONG way of string
comaprison Pointers may be compared in C using
relational operators like gt, gt, lt, lt, etc,
but they must have some relationship to be
meaningful
25Pointers and Arrays
int i145,6,7,8 int i241,2,3,4 intptr
1i1 int ptr2 ptr2ptr1 //this is ok
26Pointers and Arrays
int i145,6,7,8 What is wrong with the
following statement? i1 //The following is
ok int iptri1 iptr coutltltiptr //The
following is ok (i13) 100 // This is OK
because i1 has not changed
27Using Subscripting and Pointer Notations with
Arrays
int b 10, 20, 30, 40 int bptr b
// set bptr to point to array b cout ltlt
"Array b printed with" ltlt endl ltlt
"Array subscript notation" ltlt endl for (int
i 0 i lt 3 i) cout ltltbi ltlt
endl cout ltlt "Pointer subscript notation" ltlt
endl for (i 0 i lt 3 i) cout
ltlt bptri ltlt endl
28Using Subscripting and Pointer Notations with
Arrays
int offset cout ltlt "Pointer/offset
notation where" ltlt endl ltlt "the
pointer is the array name" ltlt endl for
(offset 0 offset lt 3 offset)
cout ltlt (b offset) ltlt endl cout
ltlt"Pointer/offset notation" ltlt endl for
(offset 0 offset lt 3 offset) cout ltlt
(bptr offset) ltlt endl
29Using Subscripting and Pointer Notations with
Arrays
int iptr int iarray4 5,6,7,8 iptr
iarray cout ltlt iptr ltlt " " ltlt iarray
ltltendl cout ltlt iptr0 ltlt " " ltlt
iarray0ltlt endl cout ltlt iptr0 ltlt "
" ltlt iarray0ltlt endl
30Pointer Arithmetic
int main() int a3 10, 20, 30
double b3 10.5, 20.5, 30.5 int iptr
double fptr int x, size3 iptr a
//name of array is a constant that points to
beginning of array fptr b for(x0
xltsize x) cout ltlt iptrx ltlt " "
ltlt fptrx ltlt '\n' cout ltlt( iptrx) ltlt "
" ltlt( fptrx) ltlt '\n' cout ltlt iptrx ltlt "
" ltlt fptrx ltlt '\n' return 0
//pointer-add example
31Pointer Arithmetic
Output 0x0012FF74 0x0012FF5C 10 10.5 10
10.5 0x0012FF78 0x0012FF64 20 20.5 11
11.5 0x0012FF7C 0x0012FF6C 30 30.5 12
12.5
32Pointer Arithmetic
int a3 1, 2, 3 int iptr iptr a
//what is the difference between iptr and
(iptr) and (iptr)? coutltltiptr
coutltltiptr coutltlt(iptr)
coutltlt(iptr) coutltlt(iptr)
coutltlt(iptr)
33Pointer Arithmetic
int a3 1, 5, 9 int iptr iptr a
//what is the difference between iptr and
(iptr) and (iptr)? Output (looking at
each statement independently)
coutltltiptr // 1 coutltltiptr // 5
coutltlt(iptr) // 1 coutltlt(iptr) // 2
coutltlt(iptr) // 1 coutltlt(iptr) // 5
34Self Test Pointer Arithmetic
int a31, 5, 9 int iptr iptr a Self
Test what is output if the statements are
executed one after the other? //Be-careful is
there array overrun? garbage values?
coutltltiptr coutltltiptr
coutltlt(iptr) coutltlt(iptr)
coutltlt(iptr) coutltlt(iptr)
35Self Test-2
What is wrong here? int myptr myptr32
36Self Test
What is output here? int x235 int a31, 5,
9 coutltlt(x) coutltlt(a1)
37Pointers Arrays
- Is anything wrong with the following
- int num3
- int i
- for(i0 ilt10 i)
-
- num i // is this OK?
- num // is this OK?
-
- Cant modify num. Cant modify a pointer constant
(an arrays name) - But this is ok
- int num3 0, 1, 2
- int p num
- (p)
38Pointers Strings
- A string constant, like an array name, is treated
by the compiler as a pointer - char p abc
- coutltltpltltendlltltp1ltltendlltltpltltendlltlt(p1)
//output? - abc bc a b
- p is assigned the base address of the character
array abc. String printed till null character,
as usual - Can we use such expressions abc1 and (abc
2) - Of course, output is b and c respectively
39Pointer Comparisons
- Pointers may be compared using relational
operators (e.g. , lt, gt). - To be meaningful, pointers should be of same type
- int num10
- int start, end
-
- start num
- end num9
-
- while(start!end)
-
- cout ltlt "Enter a number "
- cin gtgt start
- start
-
-
- start num / reset the starting pointer /
- while(start!end)
-
start
num
end
40Arrays of Pointers
- Can sure do that like other data types
- e.g. int zztop10 //array of 10 int pointers
- Now, say int var zztop3var zztop3
- Arrays of pointers to strings commonly used
- char fortunes
-
- "Soon, you will come into some money.\n",
- "A new love will enter your life.\n",
- "You will live long and prosper.\n",
- "Now is a good time to invest for the
future.\n", - "A close friend will ask for a favor.\n"
-
- cout ltlt fortunes1 ltlt endl ltlt fortunesltltendl
- ltlt (fortunes) ltlt endl ltlt (fortunes2)
ltlt endl - Output
- A new love will enter your life
41Arrays of Pointers
- Two dimensional string pointers e.g. C
dictionary - char keyword2
-
- "for", "for(initialization condition
increment)", - "if", "if(condition) ... else ...",
- "switch", "switch(value) case-list ",
- "while", "while(condition) ...",
- // add the rest of the C keywords here
- "", "" // terminate the list with nulls
-
- int main()
-
- char str80
- int i
- cout ltlt "Enter keyword "
- cin gtgt str
42Array of Strings vs. Array of Pointers
- Spot the difference
- char movies520
- Godfather, Maula Jatt,
- A Fish Called Wanda, Blade Runner,
- Spiderman
- char movies5
- Godfather, Maula Jatt,
- A Fish Called Wanda, Blade Runner,
- Spiderman
- In the first case, each column is 20 characters
wide due to the longest movie name wasted space - In the second case, the strings are placed
contiguously in memory without wasting space
pointers in the array movie point to them
43Dynamic Allocation
The new operator int x_ptr new int OR int
xptr xptr new int //heap
44Dynamic Allocation
int xptrnew int xptr 73 int x2ptr new
int x2ptr 65
45Dynamic Allocation
What is wrong here? int xptr new int xptr
73 int x2ptr x2ptr65
46Dynamic Allocation
int xptr new int xptr 73 int
x2ptr x2ptr xptr x2ptr 65
47Dynamic Allocation
//What is wrong here? int xptr new int xptr
73 int x2ptr new int x2ptr
xptr x2ptr 65 //memory leak
48Dynamic Allocation
int myptr new int(73) cout ltlt myptr delete
myptr
49Dynamic Allocation
const int SIZE 10 double ptr new
doubleSIZE /10 element array/ int i for
(i0 iltSIZE i) ptri 2.0i for
(i0 iltSIZE i) cout ltlt ptri ltlt endl
delete ptr
50Char Pointers
int intPtr int i1010,11,12,13,14,15,16,
17,18,19 char charPtr char c"We are
testing char pointers" intPtr i charPtr
c cout ltlt i ltlt" "ltlt c ltlt endl
cout ltlt intPtr ltlt " " ltlt charPtr ltlt '\n'
cout ltlt intPtr ltlt" "ltlt i0 ltlt '\n'
51char pointers
0x0012FF54 We are testing char
pointers 0x0012FF54 We are testing char
pointers 10 10
52Char Pointers
When the compiler encounters a string constant,
it stores it in the program string table and
generates a pointer to the string. char s
s "Pointers are fun to use.\n" cout ltlt s
char s2"Pointers are fun to use.\n" cout
ltlt s2
53Pointers - Dynamic Allocation
int size cingtgtsize int arraynew
intsize int i for (i0 iltsize
i) arrayi2i for (i0 iltsize
i) coutltltarrayiltltendl delete array
54Tokenizing Example
- This program scans the input string, copying
characters from the string into another array,
called token, until a space is encountered. It
prints the token and repeats the process until
null at end of string is encountered. - e.g This is a test
- This
- is
- a
- test
55SELF_TESTTokenizing Example Using Arrays
int main() char str80, token80 int i,
j cout ltlt "Enter a sentence " gets(str)
// Read a token at a time from the string.
for(i0 i) / Read characters until
either a space or the null terminator is
encountered. / for(j0 stri!'
' stri j, i) tokenj
stri tokenj '\0' // null
terminate the token cout ltlt token ltlt '\n'
if(!stri) break return 0
56Tokenizing Example Using Arrays
char str80, token80 int i0, j0
cout ltlt "Enter a sentence " cout.flush()
gets(str) // Read a token at a time from the
string.
57Tokenizing Example Using Arrays
while(stri) j0 while(stri!' '
stri) tokenjstri
i j tokenj'\0'
if(stri) i cout ltlt token ltlt '\n'
58Tokenizing Example Using Pointers
int main() char str80, token80 char p,
q cout ltlt "Enter a sentence "
gets(str) p str
59Tokenizing Example Using Pointers
// Read a token at a time from the string.
while(p) q token // set q
pointing to start of token / Read
characters until either a space or the null
terminator is encountered. / while(p!' '
p) q p q p
if(p) p // advance past the
space q '\0' // null terminate the
token cout ltlt token ltlt '\n'
return 0