Charlotte Curtis February 28, 2024
Textbook Chapter 9ish
int x = 5; int *ptr = &x; *ptr = 10; cout << "x: " << x << endl;
const
... you get the point
Textbook Chapter 9ish, still
const int NUM_STUDENTS = 20; NUM_STUDENTS = 21; // error! Can't change a const!
int x; int y = 37; const int *pci = &y; // pointer to a const int int * const cpi = &y; // const pointer to an int const int * const cpci = &y; // const pointer to a const int
int *ptr
const int *ptr
int * const ptr
const int *const ptr
All this gets rather confusing
Recall that an array is a contiguous block of memory
When arrays are declared and space is allocated, the address of the first element is associated with the name of the array, e.g.:
char A[10] strcpy(A, "Hello");
So... if A is the address of the first element, can we assign it to a pointer?
A
char A[10] = "Hello"; char *cptr = A; // no &, because A is already an address
cptr
*cptr
*cptr = 'J';
cptr++; // add one sizeof(type) to the address
Pointers can be used to iterate through arrays!
[]
int arr[10];
arr[0] = 5; *arr = 5;
i
arr[i] = 5; *(arr + i) = 5;
struct Time { int hour; int minute; };
.
Time t; t.hour = 5; // it's 5 o'clock somewhere
Time *tptr = &t;
(*tptr).hour = 5;
tptr->hour = 5;
tptr->hour++; // now it's 6 o'clock cout << tptr->hour << ':' << tptr->min << endl;
Which of the following operators can not be used with pointers?
&
*
++
/
Which statements are true about the following code snippet? Select all that apply.
x
int
p
y
int x = 0; int y = -1; const int *p = &x; cout << "x is " << x << " and y is " << y << endl;
void foo(int *iptr) { int x = 42; iptr = &x; } int main() { int *iptr = NULL; foo(iptr); cout << *iptr << endl; // what happens here? }
void foo(int *ptr); // Pointer is passed by value
Kinda confusing, let's visualize
void foo(int *&ptr); // Pointer is passed by reference
Read right-to-left: int *&ptr means "reference to pointer to int"
int *&ptr
void do_stuff(int *ptr, int n) { ptr = &n; }
void foo(int *ptr) { (*ptr)++; }
void foo(const int *ptr);
void foo(const int arr[]);
Given the following function prototypes and variable declarations:
void foo(int *ptr); void bar(int *&ptr);
int x = 0; int *iptr = &x;
Which of the following are valid?
foo(5);
foo(&5);
foo(&x);
foo(iptr);
foo(&iptr);
bar(5);
bar(&5);
bar(&x);
bar(iptr);
bar(&iptr);
typedef
typedef <type> <alias>;
typedef int * IntPtr; IntPtr iptr = NULL; void bar(IntPtr &ptr); // Can't mess up the order of & and * now
int *max(int arr[], int n);
char sentence[256]; // should be enough for a sentence, right?
new
To create a variable on the heap, use the new operator:
int *ptr; // memory for pointer is on the stack ptr = new int; // what it points at is on the heap
This does the following:
Some things to be cautious of:
ptr
delete
Textbook Section 9.2