Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 1
Introduction to C++
Lecture Set 5
Arrays and Pointers
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 2
Arrays in C++
An array is a collection of variables (of the same type) which share the same name and are distinguished from each other by using an integer index variable. You may think of this index variable as roughly like a subscript in a mathematical expression.
In C++ an array is declared using, e.g. the following syntax:
int a[10];
This declares an array of 10 int variables. Which are called a[0], a[1], a[2] ... a[9]
The array index starts a 0. Therefore int a[10]; declares 10 array elements labelled 0-9. We often refer to the number of array elements, in this case 10, as the size of the array.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 3
Arrays in C++
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 4
Arrays in C++
The big advantage of using an array over using many different variables is that by using e.g. a for-loop one can reduce many lines of repetitive to a simple expression. e.g. instead of writing
int a0,a1,a2,a3,a4,a5,a6,a7,a8,a9; a0=0; a1=0; ... a9=0;
One can have:
const int N=10; int a[N]; for(int i=0; i<N; i++){ a[i]=0; }
N.B. This is a very common construct. The counter variable i starts at 0 and counting continues which i < N , where N is the size of the array, in this case 10. Notice that the condition in the for-loop is < and NOT <=. This again is because the array index starts at 0.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 5
Arrays in C++
Using Array elements in Expressions
The array elements e.g. a[0] are used in just the same way as a normal variable, and can appear on both the right-hand and left-hand side of assignments.
The following are examples of how one can use the elements of an array.
int a[10]; ... ... a[0] = 10; a[1]+= a[0]; a[3] = a[0]*a[2]; ... ... double b[3]; ... b[1] = 0.5; b[2] = sin(b[1]);
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 6
Arrays in C++
Initialization of Arrays
One can both declare and initialize an array using the following syntax:
int a[] = { 1, 2, 3 };
Here a is automatically given the correct size of (3 in this case).
The initialization and use of arrays in demonstrated further in the example program addarray.cpp , which adds two arrays together and prints out the result.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 7
Pointers in C++
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 8
Pointers in C++
The basic idea behind pointers is fairly simple. Consider the statement:
int i=8;
This declares an int variable, which must be stored at some address in memory. The situation will look something like this:
Address Contents
0x10000000 0 0x10000001 0 0x10000002 0 0x10000003 8
There are 4 memory locations (bytes), because an int requires 4 bytes of storage.
Here the memory locations (addresses) are labelled using hexadecimal notation. int variable is allocated 4 bytes starting at the address 0x10000000 (the first 3 holds the value 0 and the last holds 8). The actual address is generally allocated by the compiler/operating system, and its value is (usually) not important.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 9
Pointers in C++
A pointer is a special variable which can hold the value of an address. Pointers allow one to lookup and manipulate addresses of variables (objects).
So in the example, a pointer to the variable i would hold the value 0x10000000.
However in C++ things are more complicated than this!
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 10
Pointers in C++
Different types of Pointers
In C++ there are different types of pointers, depending on the type of variable (object) the pointer refers to. (This is because the different types occupy different amounts of memory).
The declarations:
int* p; double* q;
Declares p to be of type pointer-to-int and q to be of type pointer-to-double
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 11
Pointers in C++
When declaring pointers white space isn't important so the statements
int* p; int *q;
Are equivalent and both declare pointers-to-ints.
But N.B. C++ is a bit confusing because in a pointer declaration the * symbol is really associated with the variable name rather than the type. Therefore if one wishes to declare two pointers at once one needs to write e.g.:
int *p,*q;
NOT
int* p,q;
The latter declares q to be an int, NOT a pointer-to-int.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 12
Pointers in C++
Using Pointers
In order to use pointers, two new operators are required.
& Take Address of
* Dereference
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 13
Pointers in C++
Consider:
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 14
Pointers in C++
This can be setup using the following code:
int paris=5; int* tokyo = &paris; // create a pointer which holds // the address of i
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 15
Pointers in C++
The situation will now look like this:
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 16
Pointers in C++
We can refer to the variable a pointer points to using the dereference operator:
*tokyo = 10; // assign 10 to the variable // pointed-to by // tokyo i.e. paris
The example program pointer.cpp further illustrates pointers.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 17
Pointer Arithmetic
key thing to understand is that pointers are just (special) types of integer variables, which can be manipulated using e.g. addition/subtraction. So one can write, for example
int i[2]; int* p = &i[0]; // p points at the first element p++; // p now points at the second element
For this to work p++ must actually changing the stored address by 4 here! (because an int uses 4 bytes of memory)
Pointers know about the size of the type they point to and the quantum for addition is sizeof (type) .
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 18
Pointer Arithmetic
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 19
Arrays and pointers
Relationship between C++ arrays and pointers
In C++ there is a close relationship between pointers and arrays. If, for example, one declares an array int a[10]; then a is automatically an int* pointer which holds the address of the first element of the array i.e. &a[0]
Therefore an alternative method of accessing array elements is via a dereferenced pointer. *(a+4) is equivalent to a[4]. This equivalence between arrays and pointers in further demonstrated in the example array.cpp
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 20
Dangers with pointers
Pointers are an extremely powerful, but by using them one can easily introduce hard-to-find bugs into one's code. In particular, because one can easily assign an arbitrary value to a pointer, it is easy to attempt to access some arbitrary address in memory. Consider the following code:
int* p = 0x80000000; *p = 10;
This tries to store the value 10 at address 0x80000000. Unless you can be sure that this address is free for use, this code will most likely result in the program crashing.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 21
Dangers with pointers
As a second example, consider the return value from a function:
int* add2( int a, int b ) { int tmp = a+b; return &tmp; }
This is valid code....but using such a function is likely to cause (hard to spot) errors, since tmp is a temporary variable, whose scope is limited to the function and its use outside its scope e.g. via a dereferenced pointer is not defined... it will most likely lead to a program crash.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 22
Pointers vs References
In many cases one can use pointers instead of references. However, wherever possible I would recommend to use of references. With pointers it is very easy to make mistakes. The advantage of pointers is that they are more flexible. ...They can be reassigned and set to 0. They are also needed to manage the free store
Use of the const declaration can make pointers safer:
const int* p;
Declares a pointer to an integer constant. While,
int i; int* const q = &i;
declares a constant pointer (properties like a reference).
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 23
Pointers as function arguments
Using pointers as function arguments
Pointers are the traditional 'C' method of providing functions with arguments that can be modified. This demonstrated by the swapp.cpp example. Notice that the syntax is more complicated than using references and the functions with a pointer argument should be called with the address of a variable. e.g. swap(&x, &y).
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 24
Arrays as function arguments
Arrays as Function Arguments
Understanding the equivalence between arrays and pointers is essential to understanding how arrays can be passed as function arguments.
If one wants to declare a function which accesses, for example, an int array then the function prototype can be declared to have an argument using the []. For example
void afun(int a[] ) { a[3] = 10; // set 4th element of the array to be 10 cout << a[3]; // print it }
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 25
Arrays as function arguments
However, an alternative, and more common syntax is to declare the argument to be an appropriate pointer. i.e.
void afun(int* a) { *(a+3) = 10; // set 4th element of the array to be 10 cout << a[3]; // print it }
Here, inside the function, the array elements can be accessed by either dereferencing the pointer, or using the [] syntax as usual. To use either of the functions, one would need to do something like:
int b[10]; // declare array ... ... afun(b); // Use the function
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 26
Arrays as function arguments
Notice that in this case there is no bounds checking on the array... the array passed as an argument could have dimension less than 4, in which case the program will behave in an undefined way, e.g. crash. Because of this it is generally a good idea to have the dimension of the array as an extra argument which can be used as protection. e.g.
void afun(int* a,int n) { if( n >= 4 ) { *(a+3) = 10; // set 4th element to be 10 cout << a[3]; // print it } else { cout << " Array is too small"; // error } }
This is demonstrated in the example: arrayarg.cpp which uses a function that prints an array.
Introduction to C++ Dr Alex Martin 2013 Lecture Set 5 Slide 27
Introduction to C++