Charlotte Curtis February 26, 2024
Textbook Chapter 6, plus off-book
#include <fstream> int main(int argc, char *argv[]) { ofstream output(argv[1]); output << "Writing to a file!\n"; output.close(); return 0; }
Textbook Chapter 9, kinda
copy_and_meow
char line[256]; while (in.getline(line, 256)) { str_replace(line, "now", "meow"); out << line << endl; }
line
in
void add_one(int arr[], int size)
[]
"It's easier to give someone your address than to make a copy of your house" -- Something I read somewhere, probably Stack Overflow
int main() { int i = 42; int j; char c = 'K'; double d = 3.14159; // ... return 0; }
The memory addresses are integers, though usually hexadecimal (base 16)
int
char
BillInfo
&
int &x = y;
type *variable_name;
type
int x; // a normal integer variable int *p; // a pointer to an integer
*
While C++ allows the * to be placed anywhere between the type and the variable, you have to be very careful:
char *cptr; // pointer to a char char* cptr2; // also a pointer to a char int *ptr1, *ptr2; // Two pointers to ints int* ptr3, ptr4; // ptr3 is a pointer to an int, ptr4 is an int
When a program runs, it is given its own isolated memory space. While you might get segmentation faults by accessing invalid memory locations, you won't bork your system or break another program.
Segmentation fault (core dumped)
gdb
int *p = 0x7ffeeb6b4a4c;
NULL
int *iptr = NULL; char *cptr = NULL;
In C++ 11, NULL was replaced with nullptr to avoid some ambiguity
nullptr
&i
000
&j
004
&c
008
&d
012
Consider the following:
int i = 42; int *iptr = &i; iptr = &j;
What just happened??
Let's draw a diagram!
Now add on:
int *iptr2; iptr2 = iptr;
int i = 42; int *iptr = &i; cout << *iptr << endl; // prints 42 *iptr = 0; cout << i << endl; // prints 0
if (iptr) { ... }
*iptr++
*(iptr++)
(*iptr)++
++
Given the following, fill in the table to the right:
int x = 24; int *iptr = &x; char c; char *cptr = &c;
x
c
iptr
cptr
&x
*iptr
*cptr
Take a few minutes to try to answer this (in groups or independently), then we'll go through the solution together