Contents
Example Code
- Code for in-class discussion
Character arrays (C-style strings)
- C-style string is a character array that ends with the null character (different than
)nullptr
- null character literal is
'\0'
- character literals are put in single quotes
'a', '\n', '$'
- string literals are put in double quotes
"Hello\n"
- Examples:
char msg[] = "Hello\n";
Note that the above is equivalent to:
char msg[] = 'H', 'e', 'l', 'l', 'o', '\n', '\0';
- the null-character is implicitly a part of any string literal; it provides an indirect means to determine a character array's size
Dynamic memory allocation
operator can be used to dynamically allocate memorynew
- Syntax —
followed by the type being allocatednew
AخAnew int; // dynamically allocates an int
new double; // dynamically allocates a double
operator deallocates memory allocated usingdelete
new
- lifetime of allocations indicated by
andnew
not by scope (e.g., memory allocated inside a function is still valid outside the function)delete
- creating an array with
— put brackets with a size after the typenew
// allocates an array of 40 ints
new int[40];
// note that the size can be a variable
// allocates an array of size doubles
new double[size];
- These statements above are not very useful by themselves, because the
allocated spaces have no names! BUT, the new operator returns
the starting address of the allocated space, and this address can be
stored in a pointer:
x
int* p; // declare a pointer p
p = new int; // dynamically allocate an int and load address into p
double* d; // declare a pointer d
d = new double; // allocate a double and store address into d
// we can also do these in single line statements
int x = 40;
int* list = new int[x];
float* numbers = new float[x+10];