Informatik W13
Levin Ceglie
Outline
- Admin
- Quiz
- Pointers
- Memory Management
Admin
Wie soll das Programm nächste Woche aussehen?
- schwierigste Fragen aus alten Quizzes kombinieren und durchgehen
- zusammen Altklausur lösen
- reguläres Programm nach Vorgabe
Pointers
Array initialization - cppreference.com
int* a = new int[5]{0, 8, 7, 2, -1};
int* ptr = a; // pointer assignment
++ptr; // shift to the right
int my_int = *ptr; // read target
ptr += 2; // shift by 2 elements
*ptr = 18; // overwrite target
int* past = a+5;
std::cout << (ptr < past) << "\n"; // compare pointersDurchgehen und erklären mit Visualisierung was im Speicher abgespeichtert ist.
Was passiert hier?
int* a = new int[5]{1,2,3,4,5};
int* p = a;
*p++ = 0;Slides (Pointers on Arrays)
Slides (Reverse Copy)
Aufgabe (Push Back)
Lösung:
void copy_range(
const int* const source_begin,
const int* const source_end,
int* const destination_begin
) {
int* dst = destination_begin;
for (const int* src = source_begin; src != source_end; ++src) {
*dst = *src;
++dst;
}
}
void our_vector::push_back(int new_element) {
int* const new_elements = new int[this->count + 1];
copy_range(this->elements, this->elements + this->count, new_elements);
delete[] this->elements;
new_elements[this->count] = new_element;
this->count++;
this->elements = new_elements;
}