Week 5 - Gemini Flashcards

(41 cards)

1
Q

What does it mean for a C-style string to be ‘null-terminated’?

A

It means the sequence of characters forming the string ends with a special null character (\0). This null character marks the end of the string and is essential for string manipulation functions to know where the string data stops.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does the required size of a character array relate to the length of the C-style string it needs to hold?

A

The character array must be at least one character larger than the string it needs to hold to accommodate the terminating null character (\0). For example, “Hello” (5 chars) needs a char array of size 6.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can you initialize a C-style string greeting with the value “Hello” during declaration in C++ (two common ways)?

A
  1. char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; \n2. char greeting[] = "Hello"; (size automatically determined to include \0)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the purpose of the strcpy(s1, s2) function from <cstring>? What are potential risks?

A

strcpy(s1, s2) copies the string s2 (including the null terminator) into string s1. Risk: If s1 is not large enough to hold s2, a buffer overflow will occur, leading to undefined behavior.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of the strcat(s1, s2) function from <cstring>? What are potential risks?

A

strcat(s1, s2) concatenates (appends) string s2 to the end of string s1. The null terminator of s1 is overwritten by the first character of s2, and a new null terminator is added at the end. Risk: If s1 is not large enough to hold its original content plus s2, a buffer overflow will occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the strlen(s1) function from <cstring> return?

A

It returns the length of the C-style string s1, which is the number of characters before the null terminator. The null terminator itself is not counted.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does the strcmp(s1, s2) function from <cstring> return, and what do the return values signify?

A

It compares two C-style strings s1 and s2 lexicographically. Returns: 0 if s1 and s2 are identical; a value less than 0 if s1 < s2; a value greater than 0 if s1 > s2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is an ‘array’ in C++? What is a key characteristic of all elements in an array?

A

An array is a collection of a fixed number of elements of the same data type stored in contiguous memory locations. Each element can be accessed using an index.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How are elements in a C++ array indexed? If an array arr has 5 elements, what are the valid indices?

A

Elements are 0-indexed. For an array with 5 elements, the valid indices are 0, 1, 2, 3, and 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you declare an integer array named numbers that can hold 10 integers?

A

int numbers[10];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you initialize all elements of an integer array myArray of size 5 to zero at the time of declaration?

A

int myArray[5] = {0}; (This specific syntax initializes all elements to 0 if at least one initializer is 0 and others are omitted for aggregate types).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What happens if you initialize an array with fewer values than its declared size, e.g., int myArray[5] = {1, 2, 3};?

A

The provided values initialize the first elements (myArray[0]=1, myArray[1]=2, myArray[2]=3), and the remaining elements are value-initialized (for int, this means they become 0).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

When passing an array to a function, what is actually passed? Why is it common to pass the array’s size as a separate argument?

A

When an array is passed to a function, typically a pointer to its first element is passed. The function does not inherently know the array’s size from this pointer alone. Therefore, the size is passed as a separate argument to allow the function to correctly iterate through the array and avoid accessing memory out of bounds.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why is it generally problematic or not recommended to directly return a statically allocated local array from a function?

A

A statically allocated local array exists on the stack and is destroyed when the function exits. Returning a pointer or reference to it would result in a dangling pointer/reference, leading to undefined behavior when accessed by the caller.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the relationship between an array name (e.g., myArray) and a pointer to its first element?

A

The array name, when used in many contexts (like assignment to a pointer or passing to a function), decays into a pointer to its first element. So, myArray is often equivalent to &myArray[0].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain how pointer arithmetic can be used to access array elements, e.g., if int *ptr = myArray;, how can *(ptr + i) be used?

A

If ptr points to the first element of myArray, then *(ptr + i) accesses the element at index i. The expression ptr + i calculates the memory address of the i-th element based on the size of the data type ptr points to.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you dynamically allocate an array of n integers using the new operator and assign it to a pointer dynArray?

A

int *dynArray = new int[n];

18
Q

How must dynamically allocated array memory (e.g., dynArray = new int[n];) be de-allocated?

A

Using the delete[] operator: delete[] dynArray; Using delete dynArray; is incorrect and leads to undefined behavior.

19
Q

What is the main advantage of using dynamic arrays (allocated with new[]) over static arrays?

A

Dynamic arrays allow their size to be determined at runtime (e.g., based on user input or other calculations), whereas the size of static arrays must be a constant known at compile time.

20
Q

If a function dynamically allocates an array and returns a pointer to it, who is typically responsible for de-allocating that memory? What is a common convention?

A

The caller of the function is typically responsible for de-allocating the memory using delete[]. A common convention is that if a function returns a pointer to dynamically allocated memory, the documentation should clearly state that the caller owns the memory and must free it.

21
Q

How can you iterate through the elements of an array using a pointer and pointer arithmetic instead of array indexing? For an array starting at begin with n elements.

A

int* end = begin + n; for (int* ptr = begin; ptr != end; ptr++) { /* use *ptr to access element */ }

22
Q

How do you declare a two-dimensional integer array matrix with 3 rows and 4 columns?

A

int matrix[3][4];

23
Q

When declaring a multi-dimensional array (e.g., int arr[][5] = {{1,2},{3,4}}), which dimensions (if any) can be omitted if it’s initialized?

A

All dimensions except the first (leftmost) must be specified. The compiler can deduce the first dimension from the number of initializers. So, int arr[][5] is valid if initialized, but int arr[3][] is not.

24
Q

What is the fundamental concept of a ‘class’ in C++ object-oriented programming?

A

A class is a blueprint for creating objects. It bundles data (member variables or attributes) and functions (member functions or methods) that operate on that data into a single user-defined type.

25
What are 'member variables' (or attributes/fields) of a class?
They are data items that belong to the class and define the state or properties of objects created from that class.
26
What are 'member functions' (or methods/operations) of a class?
They are functions that belong to the class and define the behaviors or actions that objects of the class can perform, or operations that can be done on them.
27
What is the purpose of the `public` access specifier in a class definition?
`public` members (variables or functions) of a class are accessible from anywhere outside the class where an object of that class is visible.
28
What is the purpose of the `private` access specifier in a class definition?
`private` members of a class can only be accessed by member functions of that same class or by its `friend` functions/classes. They are not directly accessible from outside the class.
29
Explain 'encapsulation' in the context of OOP and classes. How do access specifiers like `public` and `private` support it?
Encapsulation is the bundling of data (attributes) and the methods that operate on that data into a single unit (an object). It also involves restricting direct access to some of an object's components (data hiding). `private` enforces data hiding, while `public` methods provide a controlled interface to interact with the object's data.
30
How do you create an 'object' (or instance) of a class named `MyClass` and call it `myObject`?
`MyClass myObject;`
31
If `myObject` is an object of `MyClass`, and `MyClass` has a public member function `doSomething()`, how do you call this function for `myObject`?
`myObject.doSomething();` (using the dot operator).
32
If a class has private member variables, what is the common way to allow controlled read access (getter) or write access (setter) to these variables from outside the class?
By providing public member functions: a 'getter' function to return the value of a private variable, and a 'setter' function to modify its value (often with validation).
33
When defining a member function outside the class declaration, what operator is used to associate the function definition with its class? Show a general syntax.
The scope resolution operator (`::`). Syntax: `ReturnType ClassName::functionName(parameters) { /* function body */ }`.
34
For Sheet2 Problem 1: If `int x = 2; int *p = &x;`, what would `cout << &x;` print versus `cout << p;`? What about `cout << x;` versus `cout << *p;`?
`cout << &x;` and `cout << p;` would both print the memory address of `x`. `cout << x;` and `cout << *p;` would both print the value of `x` (which is 2).
35
For Sheet2 Problem 2: What does it mean to pass a 'pointer to a function' as an argument to another function (e.g., `int sum(int (*funct)(int), int n)`)?
It means the `sum` function receives the memory address of another function (`funct`). The `sum` function can then call (`funct(i)`) the passed-in function indirectly through this pointer, allowing for flexible and customizable behavior.
36
For Sheet2 Problem 3: If a function `int& f(int& a)` returns a reference to its parameter `a`, and you do `f(a)++;`, does this modify the original variable `a` passed to `f`? Why?
Yes, it modifies the original variable `a`. Because `f(a)` returns a reference to `a`, the `++` operator then acts directly on the original `a`.
37
For Sheet2 Problem 4: How can you use a pointer `int *p = a;` (where `a` is an `int` array) to read integer values into the array `a` using a loop?
Inside a loop (e.g., `for (int i=0; i> *(p+i);` or, more commonly, `cin >> p[i];` since `p[i]` is equivalent to `*(p+i)`.
38
For Sheet2 Problem 5: Describe the core difference in function signature and internal logic when implementing a `swap(num1, num2)` function using pass-by-pointer versus pass-by-reference to interchange two numbers.
Pass-by-pointer: `void swap(double* ptr1, double* ptr2)`. Inside, you'd use `*ptr1` and `*ptr2` with a temporary variable to swap values. Call: `swap(&num1, &num2);`. Pass-by-reference: `void swap(double& ref1, double& ref2)`. Inside, you'd use `ref1` and `ref2` directly with a temporary variable. Call: `swap(num1, num2);`.
39
For Sheet2 Problem 8 (implement `mystrlen`): How can you count the characters in a C-style string `const char* s` using a pointer until the null terminator is reached?
Initialize `int length = 0;`. Use a `while` loop: `while (*s != '\0')`. Inside the loop, increment the length (`length++;`) and advance the pointer (`s++;`). Return `length`.
40
For Sheet2 Problem 11 (count character occurrences): How might `strchr(s1, ch)` be useful in a loop to count occurrences of `ch` in `s1`?
`strchr(s1, ch)` returns a pointer to the first occurrence of `ch` in `s1`, or `nullptr` if not found. You can call it repeatedly. In a loop, if `strchr` finds `ch`, increment a counter. Then, to find subsequent occurrences, call `strchr` again starting from the character *after* the one just found.
41
For Sheet2 Problem 13 (generic sort): What is the role of the function pointer `int (*compare)(int, int)` in a sorting function `void sort(int a[], int n, int (*compare)(int, int))`?
The `compare` function pointer allows the `sort` function to be generic. The caller provides a specific comparison function (e.g., for ascending or descending order). The `sort` function uses this `compare` function internally to decide the relative order of elements, without being hardcoded to a single comparison logic.