Working with Memory in C ARRAYS ARRAY VARIANTS





![Creating C++ Arrays • Declaring: data. Type identifier [array. Size]; • C++ arrays have Creating C++ Arrays • Declaring: data. Type identifier [array. Size]; • C++ arrays have](https://slidetodoc.com/presentation_image/e4b6bfaba6336d9c78611523c01c70a2/image-6.jpg)


![Accessing Array Elements • The indexing operator [] gives access to any array element Accessing Array Elements • The indexing operator [] gives access to any array element](https://slidetodoc.com/presentation_image/e4b6bfaba6336d9c78611523c01c70a2/image-9.jpg)








![Using Multidimensional Arrays • Declaring: add a [size] for each additional dimension First dimension Using Multidimensional Arrays • Declaring: add a [size] for each additional dimension First dimension](https://slidetodoc.com/presentation_image/e4b6bfaba6336d9c78611523c01c70a2/image-18.jpg)












![char Arrays, aka C-Strings • Just use a basic char arr[], arr[] but keep char Arrays, aka C-Strings • Just use a basic char arr[], arr[] but keep](https://slidetodoc.com/presentation_image/e4b6bfaba6336d9c78611523c01c70a2/image-31.jpg)









































- Slides: 72
Working with Memory in C++ ARRAYS, ARRAY VARIANTS AND USAGE, STRINGS AND STREAMS, MEMORY TYPES, REFERENCES, POINTERS
Table of Contents • C++ Arrays Declaring & Initializing • Usage with Functions • Multidimensional Arrays • • Strings Arrays of char • The std: : string • • Streams, Parsing User Input, File I/O 2
Table of Contents (2) • References Declaring & Initializing • Usage • • Memory & Pointers Storage Types • Pointer Creation & Dereferencing, Pointer Arithmetic • Memory Allocation & Deallocation • C++11 Smart Pointer Basics • 3
C++ Arrays REPRESENTING MULTIPLE DATA ITEMS
Arrays • Multiple values (“elements”) under the same name & type • Stored in sequential addresses in memory • Each element in an array has an index, starting from 0 • Each element can be accessed individually through index • The array can be passed around as a single object/variable • C++ arrays are a built-in, performance-optimized language feature Note: this section will discuss so-called “static” arrays • We will discuss “dynamic” arrays in the Pointers section • 5
Creating C++ Arrays • Declaring: data. Type identifier [array. Size]; • C++ arrays have some special initialization syntax data. Type identifier[N] = {elem 0, elem 1, . . . , elem. N-1} • elem 0. . . elem. N-1 are expressions of the array’s data. Type • There can be less than N elements, but not more • N can be omitted – number of elements assumed as size • • Example: int fibonacci[5] = {1, 1, 2, 3, 5}; Index Value 0 1 1 1 2 2 3 3 4 5 6
Creating C++ Arrays - Examples • Some valid examples of C++ array initializations #include<iostream> int default. Ininitialized[2]; int main() { static int default. Initialized. Local[2]; int uninitialized[4]; int numbers[3] = {13, 42, 69}; char abc[] = {'a', 'a' + 1, 99}; char xyz[] = "xyz"; float empty. Array[] = {}; double array. With. Defaults[3] = {3. 14}; int init. List[] {13, 42, 69}; return 0; } 7
Creating C++ Arrays LIVE DEMO
Accessing Array Elements • The indexing operator [] gives access to any array element Array name comes before the operator • Element’s index comes in the operator (between the brackets) • E. g. to access the first element of arr, arr do arr[0] • • Once you access the element, treat it as a normal variable double vector 2 d[2] = {}; std: : cin >> vector 2 d[0] >> vector 2 d[1]; double length = sqrt(vector 2 d[0] * vector 2 d[0] + vector 2 d[1] * vector 2 d[1]); vector 2 d[0] /= length; vector 2 d[1] /= length; std: : cout << vector 2 d[0] << " " << vector 2 d[1] << std: : endl; 9
TIME’S TIME: UP! Quick Quiz: • You are John Snow • What will the following two code lines do? double arr[2] = {}; arr[3] = 42; a) cause a compile-time error b) cause a runtime error due to index being out of bounds c) summon demons d) you know nothing 10
C++ PITFALL: ARRAY SIZE UNKNOWN, OUTOF-BOUNDS ACCESS The C++ standard doesn’t define out-of-bounds array access behavior. C++ arrays don’t store information on their length. Program will usually attempt to access memory even if out of the array. If that part of memory is accessible to the program, it will execute whatever it is told. Otherwise an error might happen (0 x. C 00005 on Windows) 11
Accessing Array Elements LIVE DEMO
Reading-in an Array • Arrays are often read-in from some input, instead of initialized • That’s the point of arrays – to store arbitrary amounts of data • Common approach: run a for loop to read in a number of elements • Example: read-in a specified number of elements from console int main() { int numbers[actual. Count]; for (int i = 0; i < actual. Count; i++) { cin >> numbers[i]; } return 0; } 13
Reading-in Arrays LIVE DEMO
Writing-out an Array • You will commonly need to display all elements of an array • Common approach: loop over the elements • Note: need to know how long the array is • Store it in a variable or a constant const int num. Roots = 100; int main() { double square. Roots[num. Roots] = {}; for (int i = 0; i < num. Roots; i++) { square. Roots[i] = sqrt(i); } for (int i = 0; i < num. Roots; i++) { cout << square. Roots[i] << endl; } 15
Writing-out Arrays LIVE DEMO
Multidimensional Arrays • C++ can make arrays act as if they have many dimensions “As if” because they are just normal arrays which are indexed differently • Compiler enforces dimension syntax in code • • Imagine each element is actually an array 2 D (aka matrix): array of arrays (each element is a normal – 1 D – array) • 3 D array: array of 2 D arrays (each element is a 2 D array, aka matrix) • • Accessing elements is done with one indexer per dimension • 2 D array matrix 1 st element (column) of 2 nd row is matrix[1][0] • Most-common usage: making a matrix/table 17
Using Multidimensional Arrays • Declaring: add a [size] for each additional dimension First dimension can omit size • E. g. int matrix 2 Rows 3 Cols[2][3] or just matrix 2 Rows 3 Cols[][3] • • Initializing – same as normal array, but: Each dimension is an array with 1 less dimension (last is the elements) • E. g. int matrix 2 Rows 3 Cols[][3] = { {11, 12, 13}, {21, 22, 23} }; • E. g. int cube[2][3][4] = { • } • { {111, 112, 113, 114}, {121, 122, 123, 124}, {131, 132, 133, 134} }, { {211, 212, 213, 214}, {221, 222, 223, 224}, {231, 232, 233, 234} } Uninitialized values are set to defaults (as with normal arrays) 18
Multidimensional Arrays LIVE DEMO 0 1 2 3 0 111 112 113 114 0 211 212 213 214 1 122 123 124 1 222 223 224 2 131 132 133 134 2 231 232 233 234
TIME’S TIME: UP! Quick Quiz: • What will the following code do? a) cause a compile-time error b) cause a runtime error due to index being out of bounds c) set matrix[2][0] to 0 d) summon demons e) you know nothing const int rows = 4; const int cols = 3; int matrix[rows][cols] = { {11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43} }; matrix[1][3] = 0; 20
C++ PITFALL: “OUT OF BOUNDS INSIDE” MULTIDIMENSIONAL ARRAYS C++ (C actually) stores multidimensional arrays as 1 D, by joining up together 1 st dimension elements, e. g. for 2 D arrays – joining up rows into a 1 D array. This is called “row-major order” E. g. for a matrix[rows][cols] accessing [r][c] just means [r * cols + c] in the actual array 21
Row-Major Order in Multidimensional Arrays LIVE DEMO
Using C++ Arrays with Functions • Array parameters are declared the same way arrays are declared data. Type name[size_0], name[size_0] with additional [size_i] for each dimension • First dimension size can be omitted • • Functions work on the same array the caller uses i. e. if the function changes an element, the “original” array is modified • i. e. only the memory address of the array is passed, not a copy of the array • • Functions cannot return C++ “static” arrays An array created in a function is deleted when function exits • Arrays are addresses, the returned address would point to freed memory • NOTE: there are ways to return “arrays”, just not this type of arrays • 23
Using Arrays with Functions LIVE DEMO
C++11 Range-Based for Loop • Tired of writing for loops with indices to iterate over an array? • C++11 added a loop for that use-case • Syntax (for arrays): for (data. Type element : array) • Body will execute once for each element in the array • On each iteration, element will be the next item in the array int numbers[] = {13, 42, 69}; for (int number : numbers) { cout << number << endl; } 25
C++11 <array> Header • C++11 provides an alternative array, which is a bit smarter • The array class knows its size and is the same as C++ arrays • Usage: • • • #include<array> Declaring: array<int, 5> arr; is the same as int arr[5]; Declaring & Initializing: array<int, 5> arr = {1, 2, 3, 4, 5}; arr. size() gives you the size of the array Accessing elements: use the [] operator like with normal arrays 26
C++11 Range-Based for Loop and array Class LIVE DEMO
C++ Arrays – Things to Keep in Mind • Array size is fixed throughout its lifetime • Initializing an array requires its size to be known compile time i. e. the size needs to be a constant value • Note: declaring with a size coming from a variable is valid • • Arrays are addresses in memory, not objects containing data • Arrays can only be initialized – can’t be assigned with other arrays • But each of their elements can be assigned at any time • Can divide sizeof(arr) by sizeof(arr. Type) to get the length • This only works with the so-far discussed type of arrays (“static” arrays) 28
C++ Strings REPRESENTING TEXT WITH SYMBOL LITERALS, CHAR ARRAYS AND THE STD: : STRING
Representing Text in Computers • Words and text are represented as sequences of data in computers • So, text is an array of bytes, interpreted as a sequence of characters • Such a representation is called a string • How are bytes turned into characters? • • • Different standards (rulesets) – ASCII, extended ASCII, Unicode (UTF-), etc. Same array of bytes can be interpreted as differently by different standards Usually standards have some overlap (e. g. ASCII fits into Unicode) Some standards are environment related – e. g. windows codepages C++ natively supports ASCII through 8 -bit characters 30
char Arrays, aka C-Strings • Just use a basic char arr[], arr[] but keep some things in mind Should be null-terminated, i. e. end with ‘ ’, ‘ ’ which is char(0) • Can use string literal for init, which automatically places ‘ ’ at the end • If using normal array initializer, don’t forget the ‘ ’ at the end • Don’t forget the ‘ ’ counts as an element – it affects array size • • cin and cout can directly write to and read from C-Strings • char cin only works correctly if array can fit input data. Also consider spaces text[16] = {'C', '+', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g', '