
Understanding C++ Arrays: Declaration, Initialization, Usage, and More
Explore the fundamentals of working with memory in C++ through arrays, strings, streams, references, and pointers. Learn about array variants, initialization syntax, passing arrays, and array manipulation in C++.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Working with Memory in C++ 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:dataTypeidentifier[arraySize]; C++ arrays have some special initialization syntax dataType identifier[N] = {elem0, elem1, ..., elemN-1} elem0 ... elemN-1are expressions of the array s dataType 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 0 1 2 3 4 Value 1 1 2 3 5 6
Creating C++ Arrays - Examples Some valid examples of C++ array initializations #include<iostream> int defaultIninitialized[2]; int main() { static int defaultInitializedLocal[2]; int uninitialized[4]; int numbers[3] = {13, 42, 69}; char abc[] = {'a', 'a' + 1, 99}; char xyz[] = "xyz"; float emptyArray[] = {}; double arrayWithDefaults[3] = {3.14}; int initList[] {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, do arr[0] Once you access the element, treat it as a normal variable double vector2d[2] = {}; std::cin >> vector2d[0] >> vector2d[1]; double length = sqrt(vector2d[0] * vector2d[0] + vector2d[1] * vector2d[1]); vector2d[0] /= length; vector2d[1] /= length; std::cout << vector2d[0] << " " << vector2d[1] << std::endl; 9
TIMES UP! TIME: 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, OUT- OF-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 (0xC00005 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[actualCount]; for (int i = 0; i < actualCount; 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 numRoots = 100; int main() { double squareRoots[numRoots] = {}; for (int i = 0; i < numRoots; i++) { squareRoots[i] = sqrt(i); } for (int i = 0; i < numRoots; i++) { cout << squareRoots[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 2D (aka matrix): array of arrays (each element is a normal 1D array) 3D array: array of 2D arrays (each element is a 2D array, aka matrix) Accessing elements is done with one indexer per dimension 2D array matrix 1st element (column) of 2nd 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 matrix2Rows3Cols[2][3] or just matrix2Rows3Cols[][3] Initializing same as normal array, but: Each dimension is an array with 1 less dimension (last is the elements) E.g. int matrix2Rows3Cols[][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 0 1 2 3 0 1 2 3 0 111 112 113 114 0 211 212 213 214 1 121 122 123 124 1 221 222 223 224 2 131 132 133 134 2 231 232 233 234
TIMES UP! TIME: Quick Quiz: What will the following code do? a) cause a compile-time error const int rows = 4; const int cols = 3; int matrix[rows][cols] = { {11, 12, 13}, {21, 22, 23}, {31, 32, 33}, {41, 42, 43} }; b) cause a runtime error due to index being out of bounds c) set matrix[2][0] to 0 d) summon demons matrix[1][3] = 0; e) you know nothing 20
Row major 2D C++ PITFALL: OUT OF BOUNDS INSIDE MULTIDIMENSIONAL ARRAYS C++ (C actually) stores multidimensional arrays as 1D, by joining up together 1st dimension elements, e.g. for 2D arrays joining up rows into a 1D 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 dataType 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 (dataType 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(arrType) 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[], but keep some things in mind Should be null-terminated, i.e. end with \0 , which is char(0) Can use string literal for init, which automatically places \0 at the end If using normal array initializer, don t forget the \0 at the end Don t forget the \0 counts as an element it affects array size cin and cout can directly write to and read from C-Strings cin only works correctly if array can fit input data. Also consider spaces char text[16] = {'C','+','+',' ','P','r','o','g','r','a','m','m','i','n','g','\0'}; char sameText[] = {'C','+','+',' ','P','r','o','g','r','a','m','m','i','n','g', 0}; char sameTextAgain[] = "C++ Programming"; char sameTextYetAgain[16] = "C++ Programming"; 31
Text as char Arrays (C-Strings) LIVE DEMO
TIMES UP! TIME: Quick Quiz: What will the following code print? char line1[4] = {'a', 'b', 'c'}; char line2[] = {'d', 'e', 'f'}; cout << line1 << endl; cout << line2 << endl; a) It won t there will be a compile-time error b) behavior is undefined c) First line abc Second ilne def d) First line abc, second line is undefined 33
C++ PITFALL: NON- TERMINATED C- STRINGS Most C-String compatible code will expect a null- terminator when using a C-String. If there is none, the code can t know where the string ends it just continues on until it reaches null somewhere in memory But, if you give less items to array initializer than array size is the remaining items get default values, which for char is exactly the null- terminator 34
Some C-String Built-in Functions C-String functions are defined in the <cstring> header strcat(destination, source) Appends (concatenates) source C-String into destination C-String Make sure destination is long enough for source + null-terminator strlen(str) Returns the length of the C-String in str (based on the null-terminator) strstr(str, search) Returns the address (pointer) of search in str, NULL if not found int index = strstr(str, search) - str; gets you the index 35
C-String Built-in Functions LIVE DEMO
The C++ string Class The C++ string encapsulates a null-terminated C-String Provides specialized operators and methods to process text Located in the <string> header, i.e. #include<string> to use Declare like a normal variable, several ways to initialize including C-String, string literal; string is empty if no initializer given string theFoxPart = "the quick brown fox"; string theActionPart("jumps over"); char dogPartCString[] = "the lazy dog"; string sentence = theFoxPart + string("---") + theActionPart + string(3, '-') + dogPartCString; 37
string Usage Examples Let s say we have a string s1; string s2; s[index] accesses the char at that index (same as array access) s.size(); and s.length(); give us the number of chars in the string s1 + s2 concatenates (joins) the two strings s1 == s2 checks if the two strings have the same chars, s1 < s2 and s1 > s2 do lexicographical comparison s1.find(s2) returns the index of s1 in s2, or string::npos if not found s1.substr(index, length) returns a new string with chars copied from s1[index] to s1[index + length - 1] s1.c_str() and s1.data() return the underlying C-String (char array), but you should use it immediately, don t store it in a variable for later use 38
C++ Strings LIVE DEMO
Supporting Unicode in C++ char supports ASCII, string is a char array, so no Unicode there wchar_t and wstring variants of char and stringshould support system s max code point E.g. wchar_t on Unicode systems is 32-bit, but 16-bit on Windows (UTF-16) C++11 adds char16_t, char32_t, u16string and u32string All in all, built-in support is not very good just storing is ok Unicode-specific things like converting between upper and lowercase, determining size of a string, etc., are not supported properly by default Best approach: use external libraries QT, ICU, UTF8-CPP, etc. 40
Streams, Handling User Input, File I/O REPRESENTING TEXT WITH SYMBOL LITERALS, CHAR ARRAYS AND THE STD::STRING
C++ Streams We met streams in the last lecture, when we used cin and cout Offer an abstraction over data coming from or going to somewhere i.e. let us ignore details of input and output, e.g. like reading N bytes Practically speaking, streams are ways of reading/writing data A stream could be constructed for any type of data container Both for writing to and reading from that data container Arrays, strings, memory Files, network connections, the keyboard buffer, etc. 42
The stringstream The stringstream is a standard stream working over a string #include<sstream> As opposed to cin and cout which work over the console Supports both reading and writing data to the string There are also istringstream and ostringstream which only allow read or write respectively Useful for working on a string word-by-word E.g. splitting a large input into separate values E.g. reading in numbers from a string E.g. creating a string with text and numbers 43
stringstream LIVE DEMO
Handling User Input with getline() and stringstream getline(stream, targetStr) reads an entire line of text Or until a delimiter char (provided as an additional parameter) is reached From the provided stream and puts it into targetStr Avoid mixing cin>> and getline(cin, ) http://stackoverflow.com/a/18786719 We can then parse-out the targetStr with a stringstream stringstream has the same utilities as cin (e.g. whitespace skipping) Can setup the stringstream without worrying about the console If a parsing error happens (e.g. when reading an it), the error state will be on the stringstream, not on the entire standard input (cin) 45
Example: Read a line of space-separated numbers and notify the user about strings we couldn t parse as numbers: Do a getline, make a stringstream on the result Do a loop while the stringstream is valid In the loop, try to read a number If the read fails, clear the error state and read in a string instead If the errored string is empty, we just reached the end of the line If the errored string is not empty, then it must be a badly-written number store it somewhere so we can later print it to notify the user After the loop, if we have errored strings print them, otherwise we re done 46
Handling User Input LIVE DEMO
Streams to and from Files #include<fstream> provides streams for files ifstream class for input, ofstream for output, fstream for both Syntax for string reading/writing: Declare & Initialize: fstream stream(filepathStr); Or declare and open (this and the above do mostly the same thing): fstream stream; stream.open(filepathStr); Use <<, >> and getline just like with stringstream, cin and cout Stream goes out of scope file is closed. Alternatively: stream.close() Binary I/O is possible with read(), write() + some init flags 48
Streams to and from Files LIVE DEMO
Strings & Streams Things to Keep in Mind There are a lot of C-string methods for writing/reading strings sprintf writes formatted text to a C-string printf same as sprintf but writes to console sscanf reads formatted values from a C-string scanf same as scanf but reads from console Streams have many more settings and functions look them up Writing and reading to binary files (instead of text files) Seeking changing the position to read/write in the stream When streaming to files, be careful with open/closed files, stream write settings (append, overwrite), other processes using the files 50