Title: Object Oriented Systems
1Object Oriented Systems
2Todays Lecture
- This lecture we will briefly but suspiciously
depart from pointers to consider - 1. Single Dimensional Arrays
- 2. Multi Dimensional Arrays
- 3. Arrays as Parameters
- 3. C-Style Strings
- 4. The Null Terminator
- 5. String Manipulation
- 6. C String Object
-
3Arrays Quick Refresher
- An array is a collection of variables of the same
type. - These are collected together under a common name.
- In C all arrays consist of contiguous memory
locations. - The lowest address in this spread of memory will
be the first element in the array. - The highest address will be the last element.
4Single-Dimension Arrays
- The general form for declaring an array is
- type var_namesize
- For example to declare an array of 100 doubles
- double hipHip100
- An element is accessed by indexing the array
name, as follows - hipHip3 47.23
5Counting from zero
- Like Java, in C all arrays begin at 0.
- hipHip0 (first element)
- Hence if we declared an array such as.
- char p10
- Then this would declare an array that has 10
elements, p0 through to p9. - As a programmer youve gotta to learn to count
from 0..
6Arrays are pretty flexible
- Bracket notation can be used to initialise the
contents of an array - int array4 8, 67, 4, 7
- We can do simple arithmetic to generate subscript
values, e.g. - c arrayj
- arrayj2 4
- Â The exception to this is when an array is first
created, the size of the array must be an
integer, or a constant variable, e.g. - int array6
- Â double arrayj
-
7Differences with Java
- So far this looks very similar to Java. It is.
- The most significant different lies in error
checking. - C has no bounds checking on arrays. You can
overwrite either end of the area and actually
write over some other variables data. - It is the programmers job to try and make sure
this doesnt happen (unless you want it to of
course)
8Example
- For example take the following code fragment
- int count10
- int i
- for (i0 ilt100 i) counti i
In Java this code will cause an error when you
try to compile it, because the for loop will
cause the array count to overrun. In C, even
though it is incorrect, it will compile.
9The Story in Memory
- So what is actually going on when you set up an
array? - memory
- Each element is held in the next location along
in memory - Essentially what the PC is doing is looking at
the FIRST address (which is pointed to by the
variable p) and then just counts along.
10Two-Dimensional Arrays
- A two dimensional array is essentially an array
of one dimensional arrays. In general - type var_namesize1size2
- For example to declare an array of integers, of
size 10,20 - int bigGeek1020
- Elements are accessed in a very similar way to
one dimensional arrays - bigGeek211 7
11Example Noughts and Crosses
- We can also use brackets notation to set up
two-dimensional arrays. For example - char board33
- X,,O ,
- X,X, ,
- X,O,O
-
- This 3x3 array of characters, has a total of 9
elements, ranging from board00 to
board22.
12Example Graphically
- This board of elements can be represented
graphically as
SIZE 2
0
1
2
0
SIZE 1
1
2
13Example In Memory
- But this is just a graphical representation. In
memory the elements are all housed in addresses
adjacent to each other - The variable board still points to the address of
the first element.
142. Multi-Dimensional Arrays
- But the excitement doesnt end there. No Sireee.
- C can handle arrays of almost any dimension.
- The limit of dimensions that you can have, if
there is a limit, will be determined by the
specific compiler you are using. - For Example it would be quite reasonable to see
an array such as - int multi643578
15A small shortcut
- If you know exactly how many elements your array
will have , and if you fill the array when you
declare it, you can even leave out the array size
when you declare the array. - For example if you want a 5 element array you
could use the following - int myArray -200, -100, 0, 100, 200
163. Arrays as Parameters
- Passing arrays is an exception to the normal
send-by-value parameter passing. - There are several ways of passing arrays to
functions but in each case we only pass the
arrays address. This is very similar what we
just considered when we were passing variables by
reference. - Because of this we are not sending a copy - any
changes in the function will affect our original
array!
17methods for passing Arrays
- void foo1 (int x10) //sized array
-
-
-
- void foo2 (int x) //unsized array
-
-
-
- void foo3 (int x) //pointer
-
-
Here we take in an address and use x to remember
it as an array with 10 elements
but the length of the array doesnt matter as
far as C is concerned
another method we will consider later
18Passing Multidimensional Arrays
- Finally, be careful when sending
multi-dimensional arrays to functions
void mal (int x45) int
main() int hipHip333 mal(hipHip)
For a multi-dimension array we must declare all
but the first of the dimensions
194. Strings in C/C
- Odd as it might seem, there is no in built data
type in C for a string variable.life is hard
in C - Instead strings in C programs are represented
by arrays of the char data type. - For example you could assign a string to a char
array as follows -
- char text Goodbye Cruel World
- This is essentially the same as
- char text G, o, o, d, b, y, e.
. .
20Null Terminated Strings
- The terminating null is a special character that
is represent by \0, which equates to numerical 0
(not character 0). - The example from the last slide actually
allocates 20 bytes of storage in memory and
stores the string in that location. - However this is despite the fact that Goodbye
Cruel World only has 19 characters in it. - The reason that 20 bytes are allocated is that at
the end of the string is a terminating null and
C accounts for the \0 when allocating storage.
21THE POWER OF THE \0!
- Null terminated strings at first seem a lot of
hassle if you are used to Java strings. - When the program encounters a terminating null in
the character array, it interprets the location
as the end of the string. - To see how this is done, have a look at the
following code
22NULLTEST.CPP
- int main()
-
- char str I love coding.
- cout ltlt str ltlt endl
- str10 \0
- cout ltlt str ltlt endl
-
- OUTPUT I love coding.
- I love cod
23What is actually happening
- So what is happening here? The second time the
string is sent to the screen only part of the
original is displayed. - This is because as far as the computer is
concerned the string ends at character 10 in the
array. - The rest of the characters are still in storage,
but wont be displayed because we have hit the
terminating null. - before
- after
24null characters
- We could have simply assigned a zero in place of
\0 in the code listing a few slieds back. - Either is acceptable because a numerical 0 and
the char data type version, /0, are equivalent. - For example the following two lines of code are
equivalent - str7 /0 str7 0
25This all seems like hard work
- The String operations we are discussing in this
lecture are how strings are handled in C. - Most C compilers provide a class that
simplifies the difficulties inherent in the C way
of handling strings - STL - basic_string (string/wstring)
- C builder - AnsiString
- Visual C - Cstring
- Nonetheless, you do need to know about
null-terminated strings.
26String Manipulation Functions
- Also, as with Java, the operator in C will
not compare the contents of strings, only the
values of the pointers to the two strings. - However there is still a lot of support for null
terminated strings. The standard C library has
several functions for string manipulation that
will all work in your C programs. - To use these functions we need to include them.
Just like the stdio.h library, here we need to
use - include ltcstdlibgt
27Concatenation
- strcat this function concatenates the first
string with a copy of the second string. The null
terminator originally ending the first string is
overwritten, and a new null terminator added to
the end. - ...
- char str30 Tim Brailsford
- strcat(str, is very tall)
- ...
- Tim Brailsford is very tall
28Copying
- strcpy this function is used to copy one string
to another. The source string can be a variable
or a literal. Take the following code as an
example - char buff30
- strcpy(buff, This is a test)
- char buff2 A second string
- strcpy(buff, buff2)
29Careful with strcpy!
- Accidentally overwriting the end of a character
array is even easier to than with the numeric
arrays discussed earlier. - For instance, imagine youve done the following
- char buff10 A String
- // later
- strcpy(buff, This is a test.) //oops!
- Here we set up an array to hold 10 characters and
initially assigned a string requiring 9 bytes. - Later on, possibly forgetting how large the array
was, we copied a string to buff that requires 16
bytes, overwriting the by 6 bytes. - 6 bytes of memory somewhere was just erased by
this mistake.
30Length
- strlen simply returns the length of a string,
in essence it just moves along the string
character by character until it finds the null
terminator, and then returns the count. - ...
- char str40 Steve Benfords Millions
- int length strlen(str)
- ...
24
31String Manipulation Functions
- The most common ones are
- strcat(s1,s2) Concatenates a string onto the end
of s1 - strcmp(s1,s2) Compares two strings for equality
- strcpy(s1,s2) Copies s2 into s1
- strstr(s1,ch) Returns a pointer to the first
occurrence of ch - strlen(s1) Returns the length of s1
- strupr(s1) Converts s1 to uppercase
- strlwr(s1) Converts s1 to uppercase
- sprintf() Builds a string based on the parameters
32The String Object
- Up to now weve been doing it the hard way.
- We know C does not have built in support for
strings. - However standard C can handle strings in 2 ways
- The first weve looked at in detail Null
Terminated Strings (often called C-Strings) which
are complicated but good for the soul. - But the STL also provides us with a string class
too.
33The String Classes
This is a more generalised template class from
which string is derived.
basic_string
string
wstring
This is the primary class utilised. It supports
8-bit char strings.
similar class but wstring supports wide-character
strings.
34Are these Classes Necessary?
- Weve all become masters of the null-terminated
string! Why do we need a string class? - The reason is to do with what weve considered in
the last few lectures overloading. - The basic operators such as ,,- and so on
cannot be overloaded to be able to handle
null-terminated strings. For example, consider
the following code - char str150, str250, str350
- str1 Gordon //cant do str2 the
Gopher //cant do - str1 str1 str2 //error
35Part of the STL
- The STL (standard template library) has
containers, algorithms and iterators. - the String class is a container. To include the
string classes just include the ltstringgt library
at the top of your code. - 3 constructors
-
- string()
- string(const char str)
- string(const string str)
Note that the string class is all in lowercase
Takes in a null-terminated string
Takes in another string object as a parameter
all lowercase
36Now we can use
- Assignment
- Concatenation
- Concatenation Assignment
- Equality
- ! Inequality
- lt Less than
- lt Less than or equal
- gt Greater than
- gt Greater than or equal
- Subscripting
- ltlt Output
- gtgt Input
Now we dont need functions such as strcpy() and
strcat()
Just overloading the operators so they can be
used as indexing.
37Scooby-Doo Example
3 Different ways of setting up an object of the
string class
- string str1 Shaggy
- string str2(Doo)
- string str3(str2)
- str2 Scooby str3
- str3 Scrappy str3
- cout ltlt str1 ltlt says... it wasnt me
- if (str3ltstr2) cout ltlt str3 ltlt comes before ltlt
str2 - else cout ltlt str2 ltlt comes before ltlt
str3 - cout ltlt Type in your name
- cin gtgt str1
- cout ltlt str1 ltlt would have got away with it
- ltlt if it wasnt for you pesky kids
concatenation
comparison
inputting
38How long is a string?
- The most important point of this however is that
at no point do you define how long your string
will be. - string objects automatically size and re-size
themselves. - Hence it is not possible to overrun the end of as
string like you can with null terminated strings. - The most commonly used function is the .size()
method - for (i0 iltstr.size() i)
- cout ltlt stri
- cout ltlt endl
39Substrings
- Another capability provided by the class string
is substr, which returns the substring of a
string. - The substring is specified as a starting position
and a length as arguments to substr. - string date March 7, 1994 string year
date.substr(9, 4) - cout ltlt Year is ltlt Year ltlt endl
- If you go over the strings limits these values
are just set to the max possible.
40Inserting
- Of course we would use to concatenate a string.
- However this is just a specific use of the more
general append method -
- string insert(position, str, start, num)
- The start and num parameters indicate what parts
of str should be taken, to insert at place
position in the string. - string str1(Scooby DOO)
- string str2(Scrappy)
- str2.insert(2, str1, 7, 3)
- cout ltlt str2
OUTPUT ScDOOrappy
41Replacing Erasing
- The replace method is identical to insert except
it overwrites the characters that were already
there. - string str1(Scooby DOO)
- string str2(Scrappy)
- str2.insert(2, str1, 7, 3)
- cout ltlt str2
- Erase() is the method you would use to remove
characters from your string.
OUTPUT ScDOOpy
42Searching
- The string class also provides the ability to
find a substring within a string the find()
method. - Find accepts two arguments - the search string
and the starting position for the search - string scooby Wilmas lost her
glassesagain - int i scooby.find(her, 0)
- cout ltlt i is ltlt i ltlt endl
- The member function returns an integer of the
position of the first match. rfind() does the
same job but works backwards.
start point
43Getting at the C-String
- string objects can be incredibly useful - but
what if youre a purist and want a
null-terminated string. (E.g. when opening a
file). - Its easy to do. Just use.
- const char c_str() const
- This returns a point to the null terminated
character array within the string object. Take
care with it because it can easily change - Eg fstream fin( fileName.c_str() )
44And now, the end is nearrr
- Make sure youve run through the first Pointer
Exercises. This is still basic C. - Lunch Time. Go go go.
-