Notes
Notes on a website
Project maintained by BadWolf22
Hosted on GitHub Pages — Theme by mattgraham
Review
Ch 1:
Arrays
- Arrays must have the same data types inside.
- Used to implement other data structures.
- Always contiguous in memory.
- Array can not change size in most languages.
### Initializing Arrays
```c++
int A[5]; // array will be initialized by garbage
int B[5] = {1, 2, 3, 4, 500};
int C[5] = {1, 2}; // Others will be initialized by 0
int D[] = {1, 2, 3, 4, 5, 9}; //Array of 6 is created
```
### Accessing Arrays
```c++
cout << A[1] // Using index
<< 1[A] // Using index outside
<< *(A+1) // Using pointer
<< endl;
for (int i = 0; i < A.size(); i++) { // Accessing the whole array
cout << A[i] << endl;
}
```
### Array Memory Location
```c++
// This code prints the memory locations of each element of the array.
// Shows contiguous
int A[5] = {2, 4, 7, 2, 9};
for (int i = 0; i < A.size(); i++) {
cout << &A[i] << endl;
// The & means return memory location instead of value at location
}
```
Pointers: indirect addressing (think of a library and books)
- Value stored in variable (book)
- Variable stored in location (shelf)
- Address (floor number + shelf number + location number) <- used to access memory location of variable
- Name (name of bookshelf [“new books”, “math”]) <- not all locations have a name.
- Pointer (an index card for a book that tells you where to find book)
- Pointer is also a variable so it has its own (value, location, address, name)
Pointer = variable whose value is the address of another variable.
- Pointer (address type is common in C/C++)
- Operations on pointers:
- & = Referencing: Obtain address of variable from its name
- * = Dereferencing: Create a variable name for a given address
### Referencing
```c++
#include
using namespace std;
int main() {
int var1;
char var2[10];
cout << "var1 address: " << &var1 << endl;
cout << "var2 address: " << &var2 << endl;
return 0;
}
```
```c++
Output:
var1 address: 0xbfebd5c0
var2 address: 0xbfebd5c6
```
</details>
</div>
### Dereferencing
```c++
int x = 3;
int *y;
y = &x;
// *y is an l-value (left side)
// &x is a r-value (right side)
```
```c++
int x, *y;
// Initial states
// Address of x: 2000
// value of x: 500
// value of y: 8000
y = &x; // value of y: 2000
*y = 100; // value of x: 100
y = y + 10; // value of y: 2040 (2000 + 10 cells * 4 bytes/cell)
*y = 100; // Points to an unknown location, **issue**!
```
---
# Ch 2: