0% found this document useful (0 votes)
75 views51 pages

Arrays, References and Pointers

The document discusses C++ arrays, references, and pointers. It explains that arrays allow storing multiple values in a single variable. References create an alias to an existing variable, so both the variable name and reference name can access the same data. Pointers store the memory address of a variable rather than the variable's value directly. The document provides examples of declaring, initializing, accessing, and modifying arrays, references, and pointers in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views51 pages

Arrays, References and Pointers

The document discusses C++ arrays, references, and pointers. It explains that arrays allow storing multiple values in a single variable. References create an alias to an existing variable, so both the variable name and reference name can access the same data. Pointers store the memory address of a variable rather than the variable's value directly. The document provides examples of declaring, initializing, accessing, and modifying arrays, references, and pointers in C++.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

C++ Arrays, References

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 all elements in the cars array:


▪ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << cars[i] << "\n";
}

▪ 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 () {

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

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 :

▪ Thus, every element in array a is identified by an element name of the


form a[ i ][ j ], where a is the name of the array, and i and j are the
subscripts that uniquely identify each element in a.
C++ Multi-dimensional Arrays - Two-Dimensional
Arrays…
▪ Multidimensional arrays may be initialized by specifying
bracketed values for each row. Following is an array with 3
rows and each row have 4 columns:
▪ int a[3][4] = {
{0, 1, 2, 3} , // for row indexed by 0
{4, 5, 6, 7} , // for row indexed by 1
{8, 9, 10, 11} // for row indexed by 2
};
C++ Multi-dimensional Arrays - Two-Dimensional
Arrays…
▪ The nested braces, which indicate the intended row, are
optional. The following initialization is equivalent to
previous example:
▪ int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
▪ An element in 2-dimensional array is accessed by using the
subscripts, i.e., row index and column index of the array.
For example:
▪ int val = a[2][3];
▪ The above statement will take 4th element from the 3rd row
of the array.
C++ Multi-dimensional Arrays - Two-Dimensional
Arrays…
▪ #include <iostream>
using namespace std;

int main () {
// an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};

// output each array element's value


for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ ) {

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;

cout << food << "\n"; // Outputs Pizza


cout << meal << "\n"; // Outputs Pizza
C++ References - Memory Address
▪ In the example from the previous page, the & operator was
used to create a reference variable. But it can also be used
to get the memory address of a variable; which is the
location of where the variable is stored on the computer.
▪ When a variable is created in C++, a memory address is
assigned to the variable. And when we assign a value to
the variable, it is stored in this memory address.
C++ References - Memory Address…
▪ To access it, use the & operator, and the result will represent where the
variable is stored:
▪ string food = "Pizza";

cout << &food; // Outputs 0x6dfed4

▪ Note: The memory address is in hexadecimal form (0x..). Note that


you may not get the same result in your program.
C++ References - Memory Address…
▪ And why is it useful to know the memory address?
▪ References and Pointers (which you will learn about in
the next lesson) are important in C++, because they give
you the ability to manipulate the data in the computer's
memory - which can reduce the code and improve the
performance.
▪ These two features are one of the things that make C++
stand out from other programming languages,
like Python and Java.
C++ Pointers - Creating Pointers
▪ You learned from the previous lesson, that we can get
the memory address of a variable by using
the & operator:
▪ string food = "Pizza"; // A food variable of type
string
cout << food; // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food
(0x6dfed4)
▪ A pointer however, is a variable that stores the memory
address as its value.
C++ Pointers - Creating Pointers…
▪ A pointer variable points to a data type (like int or string) of the same
type, and is created with the * operator. The address of the variable
you're working with is assigned to the pointer:
▪ string food = "Pizza"; // A food variable of type string
string* ptr = &food; // A pointer variable, with the name ptr,
that stores the address of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
C++ Pointers - Creating Pointers…
▪ Example explained

▪ Create a pointer variable with the name ptr, that points


to a string variable, by using the asterisk sign * (string* ptr). Note
that the type of the pointer has to match the type of the variable
you're working with.

▪ Use the & operator to store the memory address of the variable
called food, and assign it to the pointer.

▪ Now, ptr holds the value of food's memory address.


C++ Pointers - Creating Pointers…
▪ Tip: There are three ways to declare pointer variables, but
the first way is preferred:
▪ string* mystring; // Preferred
string *mystring;
string * mystring;
C++ Pointers - Dereference
▪ Get Memory Address and Value

▪ 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>

using namespace std;


int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
C++ Pointers - Null Pointers…
▪ On most of the operating systems, programs are not permitted to
access memory at address 0 because that memory is reserved by the
operating system. However, the memory address 0 has special
significance; it signals that the pointer is not intended to point to an
accessible memory location. But by convention, if a pointer contains
the null (zero) value, it is assumed to point to nothing.
▪ To check for a null pointer you can use an if statement as follows:
if(ptr) // succeeds if p is not null
if(!ptr) // succeeds if p is null

▪ 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;

// let us have array address in pointer.


ptr = var;

for (int i = 0; i < MAX; i++) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


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>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have address of the last element in pointer.


ptr = &var[MAX-1];

for (int i = MAX; i > 0; i--) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the previous location


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>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have address of the first element in pointer.


ptr = var;
int i = 0;

while ( ptr <= &var[MAX - 1] ) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;
// point to the previous location
ptr++;
i++;
}

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>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;

for (int i = 0; i < MAX; i++) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


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;

// take the address of var


ptr = &var;

// take the address of ptr using address of operator &


pptr = &ptr;

// take the value using pptr


cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;

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;
};

▪ In the above declaration, a structure is declared by preceding the struct


keyword followed by the identifier(structure name). Inside the curly
braces, we can declare the member variables of different types.
C++ Data Structures - Defining a Structure…
▪ Here is the way you would declare the Book structure:
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
C++ Data Structures - Accessing Structure
Members
▪ To access any member of a structure, we use the member
access operator (.). The member access operator is
coded as a period between the structure variable name and
the structure member that we wish to access.
▪ You would use struct keyword to define variables of
structure type. Following is the example to explain usage
of structure:
C++ Data Structures - Accessing Structure
Members…
#include <iostream>
#include <cstring>

using namespace std;

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;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

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>

using namespace std;


void printBook( struct Books book );

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;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );

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;
}

You might also like