Arrays, References and Pointers
Arrays, References and Pointers
and Pointers
C++ Arrays
▪ Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
▪ To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it
should store:
▪ string cars[4];
▪ We have now declared a variable that holds an array of four strings. To
insert values to it, we can use an array literal - place the values in a
comma-separated list, inside curly braces:
▪ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
▪ To create an array of three integers, you could write:
▪ int myNum[3] = {10, 20, 30};
C++ Arrays - Access the Elements of an Array
▪ You access an array element by referring to the index
number.
▪ This statement accesses the value of the first
element in cars:
▪ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
▪ Note: Array indexes start with 0: [0] is the first element.
[1] is the second element, etc.
C++ Arrays - Change an Array Element
▪ To change the value of a specific element, refer to the
index number:
▪ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
C++ Arrays - Loop Through an Array
▪ You can loop through the array elements with the for loop.
▪ The following example outputs the index of each element together with
its value:
▪ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}
C++ Arrays - Loop Through an Array…
▪ #include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
return 0;
}
C++ Arrays - Loop Through an Array…
▪ This program makes use of setw() function to format the output.
When the above code is compiled and executed, it produces the
following result:
▪ Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
C++ Arrays - Omit Array Size
▪ You don't have to specify the size of the array. But if you
don't, it will only be as big as the elements that are
inserted into it:
▪ string cars[] = {"Volvo", "BMW", "Ford"}; // size of
array is always 3
▪ This is completely fine. However, the problem arise if you
want extra space for future elements. Then you have to
overwrite the existing values:
▪ string cars[] = {"Volvo", "BMW", "Ford"};
string cars[] =
{"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
C++ Arrays - Omit Array Size…
▪ If you specify the size however, the array will reserve the
extra space:
▪ string cars[5] = {"Volvo", "BMW", "Ford"}; // size of
array is 5, even though it's only three elements
inside it
▪ Now you can add a fourth and fifth element without
overwriting the others:
▪ cars[3] = "Mazda";
cars[4] = "Tesla";
C++ Arrays - Omit Elements on Declaration
▪ It is also possible to declare an array without specifying the
elements on declaration, and add them later:
▪ string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
C++ Multi-dimensional Arrays
▪ C++ allows multidimensional arrays. Here is the general
form of a multidimensional array declaration.
▪ type name[size1][size2]...[sizeN];
▪ For example, the following declaration creates a three
dimensional 5 . 10 . 4 integer array:
▪ int threedim[5][10][4];
C++ Multi-dimensional Arrays - Two-Dimensional
Arrays
▪ The simplest form of the multidimensional array is the two-dimensional
array. A two-dimensional array is, in essence, a list of one-dimensional
arrays.
▪ To declare a two-dimensional integer array of size x,y, you would write
something as follows:
▪ type arrayName [ x ][ y ];
C++ Multi-dimensional Arrays - Two-Dimensional
Arrays…
▪ A 2-dimensional array a, which contains three rows and four columns
can be shown as below :
int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
}
C++ References - Creating References
▪ A reference variable is a "reference" to an existing variable, and it is
created with the & operator:
▪ string food = "Pizza"; // food variable
string &meal = food; // reference to food
▪ Now, we can use either the variable name food or the reference
name meal to refer to the food variable:
▪ string food = "Pizza";
string &meal = food;
▪ Use the & operator to store the memory address of the variable
called food, and assign it to the pointer.
▪ In the example from the previous page, we used the pointer variable to
get the memory address of a variable (used together with
the & reference operator). However, you can also use the pointer to get
the value of the variable, by using the * operator
(the dereference operator):
▪ string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer
(0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
C++ Pointers – Dereference…
▪ Note that the * sign can be confusing here, as it does two
different things in our code:
▪ When used in declaration (string* ptr), it creates
a pointer variable.
▪ When not used in declaration, it act as a dereference
operator.
C++ Pointers - Modify the Pointer Value
▪ You can also change the pointer's value. But note that this will also change the
value of the original variable:
▪ string food = "Pizza";
string* ptr = &food;
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
C++ Pointers - Null Pointers
▪ It is always a good practice to assign the pointer NULL to a pointer
variable in case you do not have exact address to be assigned. This is
done at the time of variable declaration. A pointer that is assigned
NULL is called a null pointer.
▪ The NULL pointer is a constant with a value of zero defined in several
standard libraries, including iostream. Consider the following program:
▪ #include <iostream>
▪ Thus, if all unused pointers are given the null value and you avoid the
use of a null pointer, you can avoid the accidental misuse of an
uninitialized pointer. Many times, uninitialized variables hold some junk
values and it becomes difficult to debug the program.
C++ Pointers - Pointer Arithmetic
▪ As you understood pointer is an address which is a numeric value;
therefore, you can perform ++, --, +, and - arithmetic operations on a
pointer just as you can a numeric value.
▪ To understand pointer arithmetic, let us consider that ptr is an integer
pointer which points to the address 1000. Assuming 32-bit integers, let
us perform the following arithmetic operation on the pointer:
▪ ptr++
▪ the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer. This operation will move
the pointer to next memory location without impacting actual value at
the memory location. If ptr points to a character whose address is
1000, then above operation will point to the location 1001 because
next character will be available at 1001.
C++ Pointers - Pointer Arithmetic: Incrementing
a Pointer
▪ We prefer using a pointer in our program instead of an
array because the variable pointer can be incremented,
unlike the array name which cannot be incremented
because it is a constant pointer.
▪ The following program increments the variable pointer to
access each succeeding element of the array:
C++ Pointers - Pointer Arithmetic: Incrementing
a Pointer…
▪ #include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
return 0;
}
C++ Pointers - Pointer Arithmetic: Decrementing
a Pointer
▪ The same considerations apply to decrementing a pointer,
which decreases its value by the number of bytes of its
data type as shown:
C++ Pointers - Pointer Arithmetic: Decrementing
a Pointer…
▪ #include <iostream>
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
return 0;
}
C++ Pointers - Pointer Arithmetic: Pointer
Comparisons
▪ Pointers may be compared by using relational operators,
such as ==, <, and >. If p1 and p2 point to variables that
are related to each other, such as elements of the same
array, then p1 and p2 can be meaningfully compared.
▪ The following program modifies the previous example one
by incrementing the variable pointer so long as the address
to which it points is either less than or equal to the address
of the last element of the array, which is &var[MAX - 1]:
C++ Pointers - Pointer Arithmetic: Pointer
Comparisons…
▪ #include <iostream>
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
return 0;
}
C++ Pointers - Pointers vs Arrays
▪ Pointers and arrays are strongly related. In fact, pointers
and arrays are interchangeable in many cases.
▪ For example, a pointer that points to the beginning of an
array can access that array by using either pointer
arithmetic or array-style indexing. Consider the following
program:
C++ Pointers - Pointers vs Arrays…
▪ #include <iostream>
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
return 0;
}
C++ Pointers - Pointer to Pointer (Multiple
Indirection)
▪ A pointer to a pointer is a form of multiple indirection or a
chain of pointers. Normally, a pointer contains the address
of a variable.
▪ When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to
the location that contains the actual value as shown below.
C++ Pointers - Pointer to Pointer (Multiple
Indirection)…
▪ A variable that is a pointer to a pointer must be declared
as such. This is done by placing an additional asterisk in
front of its name.
▪ For example, following is the declaration to declare a
pointer to a pointer of type int:
▪ int **var
▪ When a target value is indirectly pointed to by a pointer to
a pointer, accessing that value requires that the asterisk
operator be applied twice, as is shown below in the
example:
C++ Pointers - Pointer to Pointer (Multiple
Indirection)…
▪ #include <iostream>
using namespace std;
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
return 0;
}
C++ Data Structures
▪ C++ arrays allow you to define variables that combine several data
items of the same kind, but structure is another user defined data
type which allows you to combine data items of different kinds.
▪ Structures are used to represent a record, suppose you want to keep
track of your books in a library. You might want to track the following
attributes about each book:
• Title
• Author
• Subject
• Book ID
C++ Data Structures - Defining a Structure
▪ To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member, for
your program. The format of the struct statement is this:
▪ struct structure_name {
member definition;
member definition;
...
member definition;
};
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
C++ Data Structures - Accessing Structure
Members…
int main() {
struct Books Book1; // Declare Book1 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
return 0;
}
C++ Data Structures - Structures as Function
Arguments
▪ You can pass a structure as a function argument in very
similar way as you pass any other variable.
▪ You would access structure variables in the similar way as
you have accessed in the above example:
C++ Data Structures - Structures as Function
Arguments…
#include <iostream>
#include <cstring>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
C++ Data Structures - Structures as Function
Arguments…
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
return 0;
}
C++ Data Structures - Structures as Function
Arguments…
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}