c++ for java programmers tutorial series quiz Flashcards
(25 cards)
dynamic vs static memory allocation
static memory allocation is done at compile time, before program is run..
dynamic memory allocation is done DURING EXECUTION.
get the address of variable “item”
&item
int *myVar;
declares a pointer called “myVar”;
pointer
- stores an address in memory
int *p = &x;
sets pointer p to the address of x
arrays in c++ differences from java
pass by value
pass in a copy of the object (this is the default)
pass by reference
pass in a reference–the address the object is at
What does this do?
int p* = &cat;
p* = 7;
- sets pointer p to be the address of cat
- deferences p, setting the thing at p to 7.
- now, cat is 7
Function prototype
the “signature” of a function placed at the top of a file (to get around the fact that a function has to have “seen” the other function above it in order to reference it
If you do NOT initialize a variable, what could happen?
example
int cat;
- it will assign a pointer for this at some memory location
- accessing cat will now give you whatever was last written to that location!
true/false: c++ will throw an error if you index out of bounds in an array
false! it will allow you to access that
an array in java is really just ______
a pointer to the first element in the array.
the ith element of the array is just pointer + size_of_int * i
the value of a boolean expression is ___ if true and ___ if false
literally anything other than 0 if true, 0 if false
advantages of declaring a number as unsigned
get a larger range of positive values out of it
evaluate this.
if (c = 0)
assigns 0 to c, returning 0 -> false always
what happens if you do this?
int arr[10] = {1,2};
arr will contain 1, 2,, then 0’s for all the other elements
what does this do?
void myMeth(const int myInt&)
method with pass-by ref arg, (you pass in the value, but it takes the ref of it) that won’t allow you to modify it in the function
- that way, you don’t have the expense of copying it, but you don’t have to worry about overwriting it
multidim array
int arr[3][2]; // 3x2 array
how do c strings work?
read along string, char by char, until null is reached.
if null not reached, it would go on forever?
like other arrays, they are unbounded
What does this do?
*(arr + 3) = 7;
look at pos of first element in arr. then look at element 3*int_size) away element address. deref that to get what it is, set the thing at that memory address to 7.
i.e. arr[3] = 7;
What does this do?
delete myVar;
mark the position in memory occupied as ok to be allocated again for dynamic allocation with new.
it does NOT set the value there to null, it does not modify the pointer.
if we try to access the pointer and look there in memory, it might give something else that’s weird now.
memory leak
when you forget to delete something when you’re done (that memory can’t be used now)
dangling pointer
a pointer that points at something that has been freed/deleted