SlideShare une entreprise Scribd logo
1  sur  138
Arrays
Ilio Catallo - info@iliocatallo.it
Outline
• Introduc*on to arrays
• Arrays vs. pointers
• Pointer arithme*c
• Arrays vs. func*ons
• The STL interface
• Gotchas with arrays
• Bibliography
Introduc)on to arrays
What is an array?
An array is a fixed size container of con,guously allocated objects
of the same type
How to define an array
Arrays are defined by specifying:
• The type common to each element
• The name of the array
• Its size
How to define an array
int numbers[5];
• Element type: ?
• Name: ?
• Size: ?
How to define an array
int numbers[5];
• Element type: int
• Name: numbers
• Size: 5
Memory layout
┌───┬───┬───┬───┬───┐
numbers:│ │ │ │ │ │
└───┴───┴───┴───┴───┘
The compiler reserves the needed amount of memory for storing
five elements of type int
Memory layout
0 ... 4
┌───┬───┬───┬───┬───┐
numbers:│ │ │ │ │ │
└───┴───┴───┴───┴───┘
Elements in the array are accessed by index
Accessing elements
The indexing operator1
[] allows accessing elements in the array
int numbers[3] = {1, 7, 13};
std::cout << numbers[0];
1
Some'mes, it is also referred to as the subscript operator
What's the type of x?
int numbers[3] = {1, 7, 13};
??? x = numbers[0];
What's the type of x?
int numbers[3] = {1, 7, 13};
int x = numbers[0];
Element type
When defining an array, the type we specify is the element type
int numbers[5];
Element type
That is, int is the type of numbers[0], ..., numbers[4]
int numbers[5];
Element type
It is possible to handle each element in numbers as any other
object of type int
int numbers[3] = {1, 7, 13};
// examples of usage
std::cout << numbers[2];
numbers[1] = 10;
What is the type of numbers?
int numbers[3] = {1, 7, 13};
For a data type T and an integral constant m, T[m] is the data type
"array of m elements of type T"
What about the type of x and y?
int x[3] = {1, 7, 13};
int y[5] = {10, 15, 18, 20, 11};
What about the type of x and y?
int x[3] = {1, 7, 13}; // x is of type int[3]
int y[5] = {10, 15, 18, 20, 11}; // y is of type int[5]
Array type is a compound type
The array type is a compound type, as it depends on two
orthogonal factors:
• The element type T
• The number of elements m
What is the output?
int x[3] = {1, 2, 3};
int y[5] = {7, 8, 9, 10, 11};
if (typeid(x) == typeid(y))
std::cout << "x and y are of the same type";
else
std::cout << "x and y are of unrelated types";
What is the output?
int x[3] = {1, 2, 3};
int y[5] = {7, 8, 9, 10, 11};
if (typeid(x) == typeid(y))
std::cout << "x and y are of the same type";
else // the else branch gets executed
std::cout << "x and y are of unrelated types";
Unrelated array types
Two arrays are of unrelated types if either the element type or the
size varies
int x[5];
int y[3];
typeid(x) == typeid(y); // false
Unrelated array types
Two arrays are of unrelated types if either the element type or the
size varies
int x[5];
char z[5];
typeid(x) == typeid(z); // false
Arrays as type costructors
Alterna(vely, one could say that [m] is a type constructor
Example
Construc)ng the type "array of 5 elements of type int"
Input type: int
Type constructor: [5]
Output type: int[5]
Does it work?
int m;
std::cin >> m;
int numbers[m];
Does it work?
// error: m should be a compile-time integral constant
int m;
std::cin >> m;
int numbers[m];
Does it work?
int m = 5;
int numbers[m];
Does it work?
// error: m should be a compile-time integral constant
int m = 5;
int numbers[m];
Array size
The size m defines the array type. As such, m must be a compile-
)me integral constant2
int numbers[5]; // correct: 5 is a literal
2
Both gcc and clang implement a non-standard extension that allows crea6ng arrays of variable size
Does the following work?
int numbers[7 + 2];
Does the following work?
// correct: 7 + 2 can be resolved at compile-time
int numbers[7 + 2];
Does the following work?
int const m = 7;
int numbers[m];
Does the following work?
// correct: m is an integral compile-time constant
int const m = 7;
int numbers[m];
Constant expressions
The only quan,,es compilers can know without execu,ng the
code are the so called constant expressions
Constant expressions
The outcome of constant expressions can be store in constant
variables
int const m = 7 + 2; // C++03
int constexpr n = 7 + 2; // C++11 & C++14
Does it work?
int p;
std::cin >> p;
int const m = p;
int numbers[m];
Does it work?
int p;
std::cin >> p;
// error: although constant, m is not
// known at compile-time
int const m = p;
int numbers[m];
Does it work?
int p = 12;
int const m = p;
int numbers[m];
Does it work?
// error: although constant, m is not
// known at compile-time
int p = 12;
int const m = p;
int numbers[m];
The std::size_t type
Formally, array sizes should be stored in constant variables of type
std::size_t
std::size_t const m = 7;
int numbers[m];
The std::size_t type
std::size_t is an unsigned integral type that can store the size
of any possible array
std::size_t const m = 7;
int numbers[m];
Arrays vs. pointers
What is the output?
int a = 7;
int* p = &a;
std::cout << p << std::endl;
What is the output?
int a = 7;
int* p = &a;
// print the address of 'a'
std::cout << p << std::endl;
Pointer to first element
Given the following array:
int numbers[5] = {1, 7, 13, 5, 9};
How can we store the address of its first element?
Pointer to first element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = ???;
Pointer to first element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = &numbers[0];
Pointer to first element
┌───┬───┬───┬───┬───┐
numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5]
└─▲─┴───┴───┴───┴───┘
│
│
│
│
┌─────┴──────┐
first: │&numbers[0] │ int*
└────────────┘
A more compact nota,on
We can obtain the same result by using a more compact nota3on.
Specifically, the following two expressions are equivalent:
int* first = &numbers[0];
int* first = numbers;
Pointer decay
Note that first is of type int*, whereas numbers is of type
int[5]
int* first = numbers;
Pointer decay
int* first = numbers;
• A temporary pointer of type int* is generated from numbers
• The content of such a pointer (i.e., the address of numbers[0])
is copied into first
• At the end of the statement, the temporary pointer is destroyed
Pointer decay
When evalua*ng an expression involving an array of type T[m]
• If the expression is valid, the compiler keeps the type as T[m]
• Otherwise, it converts T[m] to T*
Pointer decay
int numbers[5] = {1, 7, 13, 5, 9};
std::size_t s = sizeof(numbers); // numbers is
// treated as a
// int[5]
int* first = numbers; // numbers is converted
// to int*
Common trait between arrays
That is, the only common trait between the types T[m] and T[n]
is that they both decay to T*
T[m] → T*
T[n] → T*
What's the outcome?
int x[5];
int y[3];
int* first_x = x;
int* first_y = y;
typeid(x) == typeid(y); // true or false?
typeid(first_x) == typeid(first_y); // true or false?
What's the outcome?
int x[5];
int y[3];
int* first_x = x;
int* first_y = y;
typeid(x) == typeid(y); // false!
typeid(first_x) == typeid(first_y); // true!
Pointer decay
This phenomenon is called array-to-pointer decay. This is because
we lose informa2on when conver5ng
Loss of informa+on
Once converted to a pointer, there is no way to know the size of
the array from the pointer alone
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
// we CANNOT write the below 'size_from_ptr' function
// so as to obtain 5 from first
std::size_t s = size_from_ptr(first);
Pointer arithme,c
Pointer arithme,c
It is possible to introduce a set of opera2ons on pointers that
define a pointer arithme,c
• Increment and decrement
• Addi.on and subtrac.on
• Comparison
• Assignment
┌───┬───┬───┬───┬───┐
numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5]
└─▲─┴───┴───┴───┴───┘
│
│
│
│
┌─────┴──────┐
first: │&numbers[0] │ int*
└────────────┘
Increment and decrement
Pointers can be incremented (resp. decremented) in order to move
to the next (resp. previous) element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
std::cout << *first;
++first;
std::cout << *first;
Increment and decrement
Pointers can be incremented (resp. decremented) in order to move
to the next (resp. previous) element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
std::cout << *first; // output: 1
++first;
std::cout << *first; // output: 7
Addi$on and subtrac$on
Given a pointer first to the first element, the expression
first + i results in a pointer to the i-th array element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
int* third = first + 2;
int* fifth = first + 4;
std::cout << "the 3rd element is " << *third;
Addi$on and subtrac$on
┌───┬───┬───┬───┬───┐
numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5]
└─▲─┴───┴───┴───┴──▲┘
│ │
│ │
│ │
│ │
┌──┴┐ ┌┴──┐
first:│ │ int* fifth:│ │ int*
└───┘ └───┘
Addi$on and subtrac$on
Given two pointers first and last (s.t. first preceeds last),
last - first returns the number of elements in the range
[first, last)
Addi$on and subtrac$on
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers + 1; // points to 7
int* last = numbers + 3; // points to 5
std::size_t n = last - first; // n = ???
Addi$on and subtrac$on
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers + 1; // points to 7
int* last = numbers + 3; // points to 5
std::size_t n = last - first; // n = 2
Addi$on and subtrac$on
While subtrac.on between pointers is well defined, it does not
make sense to add two pointers
int p = first + last; // where is p pointing to?
Addi$on and subtrac$on: a metaphor3
3
Example taken from: h2p://stackoverflow.com/a/2935450/1849221
Addi$on and subtrac$on: a metaphor3
• 742 Evergreen Terrace + 1 = 743 Evergreen Terrace
• 742 Evergreen Terrace - 1 = 741 Evergreen Terrace
• 743 Evergreen Terrace - 741 Evergreen Terrace = 2
• 743 Evergreen Terrace + 741 Evergreen Terrace = not defined
3
Example taken from: h2p://stackoverflow.com/a/2935450/1849221
Comparison
Two pointers are equal if they point to the same element
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
int* third = first + 2;
++first; ++first;
first == third; // true!
Deriving the indexing operator
What does it print?
int numbers[5] = {1, 7, 13, 5, 9};
std::cout << *numbers + 2;
What does it print?
int numbers[5] = {1, 7, 13, 5, 9};
std::cout << *numbers + 2; // output: 3 (= 1 + 2)
What does it print?
int numbers[5] = {1, 7, 13, 5, 9};
std::cout << *(numbers + 2);
What does it print?
int numbers[5] = {1, 7, 13, 5, 9};
std::cout << *(numbers + 2); // output: 13 (numbers[2])
Accessing elements
Parentheses are important
• *numbers + 2 is the same as numbers[0] + 2
• *(numbers + 2) is the same as numbers[2]
Indexing operator
The indexing operator [] is defined in terms of pointer arithme,c
Given an array a and an index i, the opera1on a[i] is
implemented as *(a + i)
Indexing operator
In other words, C++ does not provide a proper indexing operator
for array types
Indexing operator
int numbers[5] = {1, 7, 13, 5, 9};
int* first = numbers;
std::cout << first[2]; // the same as *(first + 2);
Indexing operator
Thanks to the commuta.vity of sum, the following expressions are
equivelent:
std::cout << numbers[2]; // the same as *(numbers + 2);
std::cout << 2[numbers]; // the same as *(2 + numbers);
Arrays vs. func-ons
The sum_int func)on
Assume we need to write a func1on sum_int, which computes
the summa1on of an integer sequence
┌──────────────┐
{7, 12, 1} │ │ 20
──────────▶ sum_int ├─────────▶
│ │
└──────────────┘
Passing arrays by values
C++ does not allow passing arrays by value
Passing arrays by values
"The way arrays are passed to func3ons is an embarrassment. It dates
back to the 3me when C did not allow passing large objects to a
func3on. Even structures could not be passed by value. Within a few
years it became possible to pass structures by value, but arrays
remained in the embarrassing state."
(A. Stepanov)
An interface for sum_int
As an alterna*ve, we could design the sum_int func*on so as to
accept:
• A pointer to the first array element
• The array size
An interface for sum_int
int sum_int(??? first, ??? m);
An interface for sum_int
int sum_int(int* first, std::size_t m);
An interface for sum_int
Note that our signature has the advantage that the func2on can be
used with arrays of any size
int sum_int(int* first, std::size_t m);
Implemen'ng sum_int
int sum_int(int* first, std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += ???;
return sum;
}
Implemen'ng sum_int
int sum_int(int* first, std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += *(first + i);
return sum;
}
Invoking sum_int
int main() {
int numbers[3] = {12, 7, 1};
int* first = ???;
int r = sum_int(???, ???);
std::cout << "the elements sum up to " << r;
}
Invoking sum_int
int main() {
int numbers[3] = {12, 7, 1};
int* first = numbers;
int r = sum_int(first, 3);
std::cout << "the elements sum up to " << r;
}
Job done?
Refining sum_int
int sum_int(int* first, std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += *(first + i);
return sum;
}
Refining sum_int
int sum_int(int* first, std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += first[i];
return sum;
}
A "convenient" nota,on
In the sole context of func%on declara%on, the following two
signtures4
for sum_int are equivalent:
int sum_int(int* first, std::size_t m);
int sum_int(int first[], std::size_t m);
4
The signature int sum_int(int first[3], std::size_t m) is also possible. However, we avoid using that
as it wrongly suggests that the func;on could accept only arrays of size 3
Refining sum_int
int sum_int(int* first, std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += first[i];
return sum;
}
Refining sum_int
int sum_int(int first[], std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += first[i];
return sum;
}
Refining sum_int
int sum_int(int seq[], std::size_t m) {
int sum = 0;
for (std::size_t i = 0; i < m; ++i)
sum += seq[i];
return sum;
}
Refining sum_int
int main() {
int numbers[3] = {12, 7, 1};
int* first = numbers;
int r = sum_int(first, 3);
std::cout << "the elements sum up to " << r;
}
Refining sum_int
int main() {
int numbers[3] = {12, 7, 1};
int r = sum_int(numbers, 3);
std::cout << "the elements sum up to " << r;
}
The alterna*ve signature
Remember: adop&ng the alterna&ve signature does not mean that
the array will be passed by value
int sum_int(int seq[], std::size_t m);
The alterna*ve signature
The alterna*ve signature only gives the illusion of working with
arrays
int sum_int(int seq[], std::size_t m);
The alterna*ve signature
The parameter seq is of type int* no ma0er what
int sum_int(int seq[], std::size_t m);
The alterna*ve signature
In fact, this "convenient" nota0on is a major source of confusion
among new C/C++ programmers
int sum_int(int seq[], std::size_t m);
The STL interface
The Standard Template Library
The C++ Standard Library includes a set of algorithms and data
structures that were originally part of a third-party library, called
the Standard Template Library (STL)
The Standard Template
Library
The Standard Template Library was
invented by Alexander Stepanov in 1994
circa, and later included in the C++
Standard Library
The Standard Template Library
As an example, std::vector was originally proposed as part of
the STL, and later made into the C++ Standard Library
The STL interface
Though we will discuss in depth the STL in the future, we will now
apply its approach to computa+on in the limited case of arrays 5
5
As a ma'er of fact, the very first version of the STL algorithms was designed to work only with arrays
sum_int as we le' it
We devised the following signature for sum_int:
int sum_int(int* first, std::size_t m);
The STL interface
Let us replace the second parameter in sum_int (the array size),
with a pointer deno8ng the end of the array
int sum_int(int* first, int* last);
The STL interface
These two parameters are equivalent, as they both provide an
indica5on on where to stop inspec5ng the array
int sum_int(int* first, std::size_t m);
int sum_int(int* first, int* last);
The last pointer
Which is the last posi)on in numbers?
┌───┬───┬───┬───┬───┐
numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5]
└───┴───┴───┴───┴───┘
The last pointer
Maybe suprisingly, it is convienient to let last point to one
element past the end
The last pointer
┌───┬───┬───┬───┬───┬ ─ ┐
numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5]
└─▲─┴───┴───┴───┴───┴ ─▲┘
│ │
│ │
│ │
│ │
┌──┴┐ ┌─┴─┐
first:│ │ int* last:│ │ int*
└───┘ └───┘
sum_int as an STL algorithm
int sum_int(int* first, int* last) {
int sum = 0;
while (???) {
???
}
return sum;
}
sum_int as an STL algorithm
int sum_int(int* first, int* last) {
int sum = 0;
while (???) {
sum += *first;
++first;
}
return sum;
}
sum_int as an STL algorithm
int sum_int(int* first, int* last) {
int sum = 0;
while (first != last) {
sum += *first;
++first;
}
return sum;
}
Invoking sum_int
int main() {
int numbers[3] = {12, 7, 1};
int r = sum_int(???, ???);
std::cout << "the elements sum up to " << r;
}
Invoking sum_int
int main() {
int numbers[3] = {12, 7, 1};
int r = sum_int(numbers, numbers + 3);
std::cout << "the elements sum up to " << r;
}
std::begin and std::end
Compu&ng the beginning and the end of a sequence is so
ubiquitous that C++11 introduced two helper func+ons
int* first = std::begin(numbers);
int* last = std::end(numbers);
Invoking sum_int
int main() {
int numbers[3] = {12, 7, 1};
int r = sum_int(std::begin(numbers),
std::end(numbers));
std::cout << "the elements sum up to " << r;
}
std::accumulate
As a ma&er of fact, with sum_int we implemented a simplified
version of the standard algorithm std::accumulate
std::accumulate: an example
#include <algorithm>
#include <iostream>
int main() {
int numbers[3] = {12, 7, 1};
int r = std::accumulate(std::begin(numbers),
std::end(numbers), 0);
std::cout << "the elements sum up to " << r;
}
Gotchas with arrays
Ini$alizing an array
It is possible to use an ini#alizer list in order to ini0alize the array
int numbers[3] = {1, 7, 13};
Ini$alizing an array
When providing an ini.alizer list, the size can be omi$ed
int numbers[] = {1, 7, 13};
Does this work?
int numbers[3];
numbers = {1, 7, 13};
Assigning an array
You cannot assign an array
int numbers[3];
numbers = {1, 7, 13}; // error: assignment
Does this work?
int numbers[] = {1, 7, 13};
int other_numbers[] = numbers;
Copying an array
You cannot copy an array
int numbers[] = {1, 7, 13};
int other_numbers[] = numbers; // error, copy initialization!
Bibliography
Bibliography
• S.B. Lippman et al., C++ Primer (5th
Ed.)
• B. Stroustrup, The C++ Programming Language (4th
Ed.)
• A. Stepanov, D. Rose, From MathemaFcs to Generic
Programming
• StackOverflow FAQ, "How do I use arrays in C++?"

Contenu connexe

Tendances

Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Ali Aminian
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingAbdullah Jan
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c languagegourav kottawar
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Vanathi24
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypesMonika Sanghani
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in CTushar B Kute
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayimtiazalijoono
 

Tendances (20)

Pointer
PointerPointer
Pointer
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
8 Pointers
8 Pointers8 Pointers
8 Pointers
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Pointers_c
Pointers_cPointers_c
Pointers_c
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 

En vedette (10)

Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Regular types in C++
Regular types in C++Regular types in C++
Regular types in C++
 
Ponters
PontersPonters
Ponters
 
Pointers
PointersPointers
Pointers
 
C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
C Pointers
C PointersC Pointers
C Pointers
 

Similaire à Arrays in C++

Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptxMrhaider4
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docxjosies1
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in JavaPokequesthero
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.pptFareedIhsas
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17OdessaFrontend
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptxMrMaster11
 
Chap 2 Arrays and Structures.ppt
Chap 2  Arrays and Structures.pptChap 2  Arrays and Structures.ppt
Chap 2 Arrays and Structures.pptshashankbhadouria4
 
Chap 2 Arrays and Structures.pptx
Chap 2  Arrays and Structures.pptxChap 2  Arrays and Structures.pptx
Chap 2 Arrays and Structures.pptxshashankbhadouria4
 

Similaire à Arrays in C++ (20)

Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.ppt
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17Антихрупкий TypeScript | Odessa Frontend Meetup #17
Антихрупкий TypeScript | Odessa Frontend Meetup #17
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
PYTHON.pptx
PYTHON.pptxPYTHON.pptx
PYTHON.pptx
 
Chap 2 Arrays and Structures.ppt
Chap 2  Arrays and Structures.pptChap 2  Arrays and Structures.ppt
Chap 2 Arrays and Structures.ppt
 
Chap 2 Arrays and Structures.pptx
Chap 2  Arrays and Structures.pptxChap 2  Arrays and Structures.pptx
Chap 2 Arrays and Structures.pptx
 
Python
PythonPython
Python
 

Plus de Ilio Catallo

Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
Spring MVC - Wiring the different layers
Spring MVC -  Wiring the different layersSpring MVC -  Wiring the different layers
Spring MVC - Wiring the different layersIlio Catallo
 
Java and Java platforms
Java and Java platformsJava and Java platforms
Java and Java platformsIlio Catallo
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web FormsIlio Catallo
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The BasicsIlio Catallo
 
Web application architecture
Web application architectureWeb application architecture
Web application architectureIlio Catallo
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To SpringIlio Catallo
 
Gestione della memoria in C++
Gestione della memoria in C++Gestione della memoria in C++
Gestione della memoria in C++Ilio Catallo
 
Puntatori e Riferimenti
Puntatori e RiferimentiPuntatori e Riferimenti
Puntatori e RiferimentiIlio Catallo
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag LibraryIlio Catallo
 
Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Ilio Catallo
 
Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Ilio Catallo
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3Ilio Catallo
 
Community Detection
Community DetectionCommunity Detection
Community DetectionIlio Catallo
 
WWW12 - The CUbRIK Project
WWW12 - The CUbRIK ProjectWWW12 - The CUbRIK Project
WWW12 - The CUbRIK ProjectIlio Catallo
 

Plus de Ilio Catallo (17)

Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
Spring MVC - Wiring the different layers
Spring MVC -  Wiring the different layersSpring MVC -  Wiring the different layers
Spring MVC - Wiring the different layers
 
Java and Java platforms
Java and Java platformsJava and Java platforms
Java and Java platforms
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web Forms
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
 
Gestione della memoria in C++
Gestione della memoria in C++Gestione della memoria in C++
Gestione della memoria in C++
 
Array in C++
Array in C++Array in C++
Array in C++
 
Puntatori e Riferimenti
Puntatori e RiferimentiPuntatori e Riferimenti
Puntatori e Riferimenti
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
JSP Standard Tag Library
JSP Standard Tag LibraryJSP Standard Tag Library
JSP Standard Tag Library
 
Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3Internationalization in Jakarta Struts 1.3
Internationalization in Jakarta Struts 1.3
 
Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3Validation in Jakarta Struts 1.3
Validation in Jakarta Struts 1.3
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
Community Detection
Community DetectionCommunity Detection
Community Detection
 
WWW12 - The CUbRIK Project
WWW12 - The CUbRIK ProjectWWW12 - The CUbRIK Project
WWW12 - The CUbRIK Project
 

Dernier

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Dernier (20)

Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

Arrays in C++

  • 1. Arrays Ilio Catallo - info@iliocatallo.it
  • 2. Outline • Introduc*on to arrays • Arrays vs. pointers • Pointer arithme*c • Arrays vs. func*ons • The STL interface • Gotchas with arrays • Bibliography
  • 4. What is an array? An array is a fixed size container of con,guously allocated objects of the same type
  • 5. How to define an array Arrays are defined by specifying: • The type common to each element • The name of the array • Its size
  • 6. How to define an array int numbers[5]; • Element type: ? • Name: ? • Size: ?
  • 7. How to define an array int numbers[5]; • Element type: int • Name: numbers • Size: 5
  • 8. Memory layout ┌───┬───┬───┬───┬───┐ numbers:│ │ │ │ │ │ └───┴───┴───┴───┴───┘ The compiler reserves the needed amount of memory for storing five elements of type int
  • 9. Memory layout 0 ... 4 ┌───┬───┬───┬───┬───┐ numbers:│ │ │ │ │ │ └───┴───┴───┴───┴───┘ Elements in the array are accessed by index
  • 10. Accessing elements The indexing operator1 [] allows accessing elements in the array int numbers[3] = {1, 7, 13}; std::cout << numbers[0]; 1 Some'mes, it is also referred to as the subscript operator
  • 11. What's the type of x? int numbers[3] = {1, 7, 13}; ??? x = numbers[0];
  • 12. What's the type of x? int numbers[3] = {1, 7, 13}; int x = numbers[0];
  • 13. Element type When defining an array, the type we specify is the element type int numbers[5];
  • 14. Element type That is, int is the type of numbers[0], ..., numbers[4] int numbers[5];
  • 15. Element type It is possible to handle each element in numbers as any other object of type int int numbers[3] = {1, 7, 13}; // examples of usage std::cout << numbers[2]; numbers[1] = 10;
  • 16. What is the type of numbers? int numbers[3] = {1, 7, 13};
  • 17. For a data type T and an integral constant m, T[m] is the data type "array of m elements of type T"
  • 18. What about the type of x and y? int x[3] = {1, 7, 13}; int y[5] = {10, 15, 18, 20, 11};
  • 19. What about the type of x and y? int x[3] = {1, 7, 13}; // x is of type int[3] int y[5] = {10, 15, 18, 20, 11}; // y is of type int[5]
  • 20. Array type is a compound type The array type is a compound type, as it depends on two orthogonal factors: • The element type T • The number of elements m
  • 21. What is the output? int x[3] = {1, 2, 3}; int y[5] = {7, 8, 9, 10, 11}; if (typeid(x) == typeid(y)) std::cout << "x and y are of the same type"; else std::cout << "x and y are of unrelated types";
  • 22. What is the output? int x[3] = {1, 2, 3}; int y[5] = {7, 8, 9, 10, 11}; if (typeid(x) == typeid(y)) std::cout << "x and y are of the same type"; else // the else branch gets executed std::cout << "x and y are of unrelated types";
  • 23. Unrelated array types Two arrays are of unrelated types if either the element type or the size varies int x[5]; int y[3]; typeid(x) == typeid(y); // false
  • 24. Unrelated array types Two arrays are of unrelated types if either the element type or the size varies int x[5]; char z[5]; typeid(x) == typeid(z); // false
  • 25. Arrays as type costructors Alterna(vely, one could say that [m] is a type constructor
  • 26. Example Construc)ng the type "array of 5 elements of type int" Input type: int Type constructor: [5] Output type: int[5]
  • 27. Does it work? int m; std::cin >> m; int numbers[m];
  • 28. Does it work? // error: m should be a compile-time integral constant int m; std::cin >> m; int numbers[m];
  • 29. Does it work? int m = 5; int numbers[m];
  • 30. Does it work? // error: m should be a compile-time integral constant int m = 5; int numbers[m];
  • 31. Array size The size m defines the array type. As such, m must be a compile- )me integral constant2 int numbers[5]; // correct: 5 is a literal 2 Both gcc and clang implement a non-standard extension that allows crea6ng arrays of variable size
  • 32. Does the following work? int numbers[7 + 2];
  • 33. Does the following work? // correct: 7 + 2 can be resolved at compile-time int numbers[7 + 2];
  • 34. Does the following work? int const m = 7; int numbers[m];
  • 35. Does the following work? // correct: m is an integral compile-time constant int const m = 7; int numbers[m];
  • 36. Constant expressions The only quan,,es compilers can know without execu,ng the code are the so called constant expressions
  • 37. Constant expressions The outcome of constant expressions can be store in constant variables int const m = 7 + 2; // C++03 int constexpr n = 7 + 2; // C++11 & C++14
  • 38. Does it work? int p; std::cin >> p; int const m = p; int numbers[m];
  • 39. Does it work? int p; std::cin >> p; // error: although constant, m is not // known at compile-time int const m = p; int numbers[m];
  • 40. Does it work? int p = 12; int const m = p; int numbers[m];
  • 41. Does it work? // error: although constant, m is not // known at compile-time int p = 12; int const m = p; int numbers[m];
  • 42. The std::size_t type Formally, array sizes should be stored in constant variables of type std::size_t std::size_t const m = 7; int numbers[m];
  • 43. The std::size_t type std::size_t is an unsigned integral type that can store the size of any possible array std::size_t const m = 7; int numbers[m];
  • 45. What is the output? int a = 7; int* p = &a; std::cout << p << std::endl;
  • 46. What is the output? int a = 7; int* p = &a; // print the address of 'a' std::cout << p << std::endl;
  • 47. Pointer to first element Given the following array: int numbers[5] = {1, 7, 13, 5, 9}; How can we store the address of its first element?
  • 48. Pointer to first element int numbers[5] = {1, 7, 13, 5, 9}; int* first = ???;
  • 49. Pointer to first element int numbers[5] = {1, 7, 13, 5, 9}; int* first = &numbers[0];
  • 50. Pointer to first element ┌───┬───┬───┬───┬───┐ numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5] └─▲─┴───┴───┴───┴───┘ │ │ │ │ ┌─────┴──────┐ first: │&numbers[0] │ int* └────────────┘
  • 51. A more compact nota,on We can obtain the same result by using a more compact nota3on. Specifically, the following two expressions are equivalent: int* first = &numbers[0]; int* first = numbers;
  • 52. Pointer decay Note that first is of type int*, whereas numbers is of type int[5] int* first = numbers;
  • 53. Pointer decay int* first = numbers; • A temporary pointer of type int* is generated from numbers • The content of such a pointer (i.e., the address of numbers[0]) is copied into first • At the end of the statement, the temporary pointer is destroyed
  • 54. Pointer decay When evalua*ng an expression involving an array of type T[m] • If the expression is valid, the compiler keeps the type as T[m] • Otherwise, it converts T[m] to T*
  • 55. Pointer decay int numbers[5] = {1, 7, 13, 5, 9}; std::size_t s = sizeof(numbers); // numbers is // treated as a // int[5] int* first = numbers; // numbers is converted // to int*
  • 56. Common trait between arrays That is, the only common trait between the types T[m] and T[n] is that they both decay to T* T[m] → T* T[n] → T*
  • 57. What's the outcome? int x[5]; int y[3]; int* first_x = x; int* first_y = y; typeid(x) == typeid(y); // true or false? typeid(first_x) == typeid(first_y); // true or false?
  • 58. What's the outcome? int x[5]; int y[3]; int* first_x = x; int* first_y = y; typeid(x) == typeid(y); // false! typeid(first_x) == typeid(first_y); // true!
  • 59. Pointer decay This phenomenon is called array-to-pointer decay. This is because we lose informa2on when conver5ng
  • 60. Loss of informa+on Once converted to a pointer, there is no way to know the size of the array from the pointer alone int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; // we CANNOT write the below 'size_from_ptr' function // so as to obtain 5 from first std::size_t s = size_from_ptr(first);
  • 62. Pointer arithme,c It is possible to introduce a set of opera2ons on pointers that define a pointer arithme,c • Increment and decrement • Addi.on and subtrac.on • Comparison • Assignment
  • 63. ┌───┬───┬───┬───┬───┐ numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5] └─▲─┴───┴───┴───┴───┘ │ │ │ │ ┌─────┴──────┐ first: │&numbers[0] │ int* └────────────┘
  • 64. Increment and decrement Pointers can be incremented (resp. decremented) in order to move to the next (resp. previous) element int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; std::cout << *first; ++first; std::cout << *first;
  • 65. Increment and decrement Pointers can be incremented (resp. decremented) in order to move to the next (resp. previous) element int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; std::cout << *first; // output: 1 ++first; std::cout << *first; // output: 7
  • 66. Addi$on and subtrac$on Given a pointer first to the first element, the expression first + i results in a pointer to the i-th array element int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; int* third = first + 2; int* fifth = first + 4; std::cout << "the 3rd element is " << *third;
  • 67. Addi$on and subtrac$on ┌───┬───┬───┬───┬───┐ numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5] └─▲─┴───┴───┴───┴──▲┘ │ │ │ │ │ │ │ │ ┌──┴┐ ┌┴──┐ first:│ │ int* fifth:│ │ int* └───┘ └───┘
  • 68. Addi$on and subtrac$on Given two pointers first and last (s.t. first preceeds last), last - first returns the number of elements in the range [first, last)
  • 69. Addi$on and subtrac$on int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers + 1; // points to 7 int* last = numbers + 3; // points to 5 std::size_t n = last - first; // n = ???
  • 70. Addi$on and subtrac$on int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers + 1; // points to 7 int* last = numbers + 3; // points to 5 std::size_t n = last - first; // n = 2
  • 71. Addi$on and subtrac$on While subtrac.on between pointers is well defined, it does not make sense to add two pointers int p = first + last; // where is p pointing to?
  • 72. Addi$on and subtrac$on: a metaphor3 3 Example taken from: h2p://stackoverflow.com/a/2935450/1849221
  • 73. Addi$on and subtrac$on: a metaphor3 • 742 Evergreen Terrace + 1 = 743 Evergreen Terrace • 742 Evergreen Terrace - 1 = 741 Evergreen Terrace • 743 Evergreen Terrace - 741 Evergreen Terrace = 2 • 743 Evergreen Terrace + 741 Evergreen Terrace = not defined 3 Example taken from: h2p://stackoverflow.com/a/2935450/1849221
  • 74. Comparison Two pointers are equal if they point to the same element int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; int* third = first + 2; ++first; ++first; first == third; // true!
  • 76. What does it print? int numbers[5] = {1, 7, 13, 5, 9}; std::cout << *numbers + 2;
  • 77. What does it print? int numbers[5] = {1, 7, 13, 5, 9}; std::cout << *numbers + 2; // output: 3 (= 1 + 2)
  • 78. What does it print? int numbers[5] = {1, 7, 13, 5, 9}; std::cout << *(numbers + 2);
  • 79. What does it print? int numbers[5] = {1, 7, 13, 5, 9}; std::cout << *(numbers + 2); // output: 13 (numbers[2])
  • 80. Accessing elements Parentheses are important • *numbers + 2 is the same as numbers[0] + 2 • *(numbers + 2) is the same as numbers[2]
  • 81. Indexing operator The indexing operator [] is defined in terms of pointer arithme,c Given an array a and an index i, the opera1on a[i] is implemented as *(a + i)
  • 82. Indexing operator In other words, C++ does not provide a proper indexing operator for array types
  • 83. Indexing operator int numbers[5] = {1, 7, 13, 5, 9}; int* first = numbers; std::cout << first[2]; // the same as *(first + 2);
  • 84. Indexing operator Thanks to the commuta.vity of sum, the following expressions are equivelent: std::cout << numbers[2]; // the same as *(numbers + 2); std::cout << 2[numbers]; // the same as *(2 + numbers);
  • 86. The sum_int func)on Assume we need to write a func1on sum_int, which computes the summa1on of an integer sequence ┌──────────────┐ {7, 12, 1} │ │ 20 ──────────▶ sum_int ├─────────▶ │ │ └──────────────┘
  • 87. Passing arrays by values C++ does not allow passing arrays by value
  • 88. Passing arrays by values "The way arrays are passed to func3ons is an embarrassment. It dates back to the 3me when C did not allow passing large objects to a func3on. Even structures could not be passed by value. Within a few years it became possible to pass structures by value, but arrays remained in the embarrassing state." (A. Stepanov)
  • 89. An interface for sum_int As an alterna*ve, we could design the sum_int func*on so as to accept: • A pointer to the first array element • The array size
  • 90. An interface for sum_int int sum_int(??? first, ??? m);
  • 91. An interface for sum_int int sum_int(int* first, std::size_t m);
  • 92. An interface for sum_int Note that our signature has the advantage that the func2on can be used with arrays of any size int sum_int(int* first, std::size_t m);
  • 93. Implemen'ng sum_int int sum_int(int* first, std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += ???; return sum; }
  • 94. Implemen'ng sum_int int sum_int(int* first, std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += *(first + i); return sum; }
  • 95. Invoking sum_int int main() { int numbers[3] = {12, 7, 1}; int* first = ???; int r = sum_int(???, ???); std::cout << "the elements sum up to " << r; }
  • 96. Invoking sum_int int main() { int numbers[3] = {12, 7, 1}; int* first = numbers; int r = sum_int(first, 3); std::cout << "the elements sum up to " << r; }
  • 98. Refining sum_int int sum_int(int* first, std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += *(first + i); return sum; }
  • 99. Refining sum_int int sum_int(int* first, std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += first[i]; return sum; }
  • 100. A "convenient" nota,on In the sole context of func%on declara%on, the following two signtures4 for sum_int are equivalent: int sum_int(int* first, std::size_t m); int sum_int(int first[], std::size_t m); 4 The signature int sum_int(int first[3], std::size_t m) is also possible. However, we avoid using that as it wrongly suggests that the func;on could accept only arrays of size 3
  • 101. Refining sum_int int sum_int(int* first, std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += first[i]; return sum; }
  • 102. Refining sum_int int sum_int(int first[], std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += first[i]; return sum; }
  • 103. Refining sum_int int sum_int(int seq[], std::size_t m) { int sum = 0; for (std::size_t i = 0; i < m; ++i) sum += seq[i]; return sum; }
  • 104. Refining sum_int int main() { int numbers[3] = {12, 7, 1}; int* first = numbers; int r = sum_int(first, 3); std::cout << "the elements sum up to " << r; }
  • 105. Refining sum_int int main() { int numbers[3] = {12, 7, 1}; int r = sum_int(numbers, 3); std::cout << "the elements sum up to " << r; }
  • 106. The alterna*ve signature Remember: adop&ng the alterna&ve signature does not mean that the array will be passed by value int sum_int(int seq[], std::size_t m);
  • 107. The alterna*ve signature The alterna*ve signature only gives the illusion of working with arrays int sum_int(int seq[], std::size_t m);
  • 108. The alterna*ve signature The parameter seq is of type int* no ma0er what int sum_int(int seq[], std::size_t m);
  • 109. The alterna*ve signature In fact, this "convenient" nota0on is a major source of confusion among new C/C++ programmers int sum_int(int seq[], std::size_t m);
  • 111. The Standard Template Library The C++ Standard Library includes a set of algorithms and data structures that were originally part of a third-party library, called the Standard Template Library (STL)
  • 112. The Standard Template Library The Standard Template Library was invented by Alexander Stepanov in 1994 circa, and later included in the C++ Standard Library
  • 113. The Standard Template Library As an example, std::vector was originally proposed as part of the STL, and later made into the C++ Standard Library
  • 114. The STL interface Though we will discuss in depth the STL in the future, we will now apply its approach to computa+on in the limited case of arrays 5 5 As a ma'er of fact, the very first version of the STL algorithms was designed to work only with arrays
  • 115. sum_int as we le' it We devised the following signature for sum_int: int sum_int(int* first, std::size_t m);
  • 116. The STL interface Let us replace the second parameter in sum_int (the array size), with a pointer deno8ng the end of the array int sum_int(int* first, int* last);
  • 117. The STL interface These two parameters are equivalent, as they both provide an indica5on on where to stop inspec5ng the array int sum_int(int* first, std::size_t m); int sum_int(int* first, int* last);
  • 118. The last pointer Which is the last posi)on in numbers? ┌───┬───┬───┬───┬───┐ numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5] └───┴───┴───┴───┴───┘
  • 119. The last pointer Maybe suprisingly, it is convienient to let last point to one element past the end
  • 120. The last pointer ┌───┬───┬───┬───┬───┬ ─ ┐ numbers: │ 1 │ 7 │13 │ 5 │ 9 │ int[5] └─▲─┴───┴───┴───┴───┴ ─▲┘ │ │ │ │ │ │ │ │ ┌──┴┐ ┌─┴─┐ first:│ │ int* last:│ │ int* └───┘ └───┘
  • 121. sum_int as an STL algorithm int sum_int(int* first, int* last) { int sum = 0; while (???) { ??? } return sum; }
  • 122. sum_int as an STL algorithm int sum_int(int* first, int* last) { int sum = 0; while (???) { sum += *first; ++first; } return sum; }
  • 123. sum_int as an STL algorithm int sum_int(int* first, int* last) { int sum = 0; while (first != last) { sum += *first; ++first; } return sum; }
  • 124. Invoking sum_int int main() { int numbers[3] = {12, 7, 1}; int r = sum_int(???, ???); std::cout << "the elements sum up to " << r; }
  • 125. Invoking sum_int int main() { int numbers[3] = {12, 7, 1}; int r = sum_int(numbers, numbers + 3); std::cout << "the elements sum up to " << r; }
  • 126. std::begin and std::end Compu&ng the beginning and the end of a sequence is so ubiquitous that C++11 introduced two helper func+ons int* first = std::begin(numbers); int* last = std::end(numbers);
  • 127. Invoking sum_int int main() { int numbers[3] = {12, 7, 1}; int r = sum_int(std::begin(numbers), std::end(numbers)); std::cout << "the elements sum up to " << r; }
  • 128. std::accumulate As a ma&er of fact, with sum_int we implemented a simplified version of the standard algorithm std::accumulate
  • 129. std::accumulate: an example #include <algorithm> #include <iostream> int main() { int numbers[3] = {12, 7, 1}; int r = std::accumulate(std::begin(numbers), std::end(numbers), 0); std::cout << "the elements sum up to " << r; }
  • 131. Ini$alizing an array It is possible to use an ini#alizer list in order to ini0alize the array int numbers[3] = {1, 7, 13};
  • 132. Ini$alizing an array When providing an ini.alizer list, the size can be omi$ed int numbers[] = {1, 7, 13};
  • 133. Does this work? int numbers[3]; numbers = {1, 7, 13};
  • 134. Assigning an array You cannot assign an array int numbers[3]; numbers = {1, 7, 13}; // error: assignment
  • 135. Does this work? int numbers[] = {1, 7, 13}; int other_numbers[] = numbers;
  • 136. Copying an array You cannot copy an array int numbers[] = {1, 7, 13}; int other_numbers[] = numbers; // error, copy initialization!
  • 138. Bibliography • S.B. Lippman et al., C++ Primer (5th Ed.) • B. Stroustrup, The C++ Programming Language (4th Ed.) • A. Stepanov, D. Rose, From MathemaFcs to Generic Programming • StackOverflow FAQ, "How do I use arrays in C++?"