CS Week 5- Arrays and Intro to Pointers Flashcards
array
an ordered list of items of a given data type
element
each item in an array
declaration of an array
dataType arrayName [numElements];
index type
int type only
to check if index is valid
if (nth >= 1 && nth <= 5) { }
iterate how many times through a loop
the size of the array that you should keep track up
array initilization
int myArray[3] = {5, 6, 7};
array vs vector
declaration and accessed and differences
Array -
Declaration: int myList[#];
Accessed: myList[i];
Vector-
Declaration: vector<int> myList(#)
Accessed: myList.at(0);</int>
Arrays have simpler syntax but do not have .size() feature
Vectors are safer
an array as a paramter
uses the [], but argument does not
passes in an array
reversing an array
loop numElements/2 times
tempVal = a[i];
a[i] = a[numElements - 1- i];
a[numElements - 1-i] = tempVal;
two dimensional array
int myArray [R][C]
row major order
compiler maps 2-dimensional array elements to one-dimensional memory, each row following the previous row
two-dimensional array initialization
int nums [2][3] = { {2,4,6}, {5,6,7} };
Or to make it more visible
int nums [2][3] = {
{2, 4, 6},
{5, 6, 7}
};
access row n and column m
array[n-1][m-1]
pointer
a variable that holds a memory address (rather than holding data)
what does the data type of a pointer mean
the type of address that is held in the pointer
declare and initialize it
int* pointer = &someVar;
dereference operator
*
is prepended to a pointers variable name to retrieve the data to which the pointer variable points
null pointer
When a pointer is declared, the pointer variable holds an unknown address until the pointer is initialized
Null means nothing
int* pointer = nullptr;
check if null
in notes
change the value of the variable that the pointer is pointing to
*p = 888;
use/cout the pointer/the value the pointer is poitning to
cout «_space;*p;
other ways to dereference a pointer
*p = 44;
p[0] = 444;
p[-1]
go to where p is pointing and advance 0/-1 steps
p = p + 1
*p = 555;
*(p+1) = 8888;
other ways to initialize a pointer
int* q = p + 5;
int* q = A + 5;
int* q = &(A[5]);
int* q = A;
double pointer and const
int** pp = &p
pp points to the same place as p
int * const * const what;
-a const pointer to a const pointer to an int (what)
-can change the value of what you are pointing to
const int * const * const what;
can not change what the pointer is pointing to
K, Meg, Gig, Tera
K = 2^10
Meg = 2 ^10 K = 2 ^20
Gig = 2 ^10 M = 2 ^ 30
Tera = 2 ^ 10 G = 2 ^ 40
passing in an array or pointer into a funciton
int A[]
int* A
- no need for reference because * is one kinda
int* A, unsigned n;
let people know what passing in
n = offset if A is a pointer, size of pointer is a collection of data