Week 4 - Gemini Flashcards

(36 cards)

1
Q

What is a pointer variable in C++, and what does it store?

A

A pointer variable is a variable that stores a memory address. This address can be the location of another variable, another pointer, or a function in memory.

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

How do you declare a pointer to an integer variable named ‘p_num’?

A

int *p_num; (or int* p_num; or int * p_num;)”

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

What is the ‘address-of’ operator (&), and how is it used with pointers?

A

The address-of operator (&) returns the memory address of a variable. It’s used to initialize a pointer to point to that variable, e.g., p_num = &my_var;.

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

What is the ‘dereferencing’ or ‘indirection’ operator (*), and how is it used with pointers?

A

The dereferencing operator (*), when applied to a pointer, returns the value stored at the memory address the pointer is pointing to. E.g., value = *p_num; reads the value, and *p_num = 10; writes to the value.

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

Explain the difference in meaning of the asterisk (*) in a pointer declaration (e.g., int *ptr;) versus in an expression (e.g., *ptr = 5;).

A

In a declaration (int *ptr;), the * indicates that ptr is a pointer variable. In an expression (*ptr = 5;), the * is the dereferencing operator, accessing the value at the address stored in ptr.

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

Can an int* pointer hold the address of a double variable? Why or why not?

A

No. A pointer is associated with a specific data type. An int* can only hold the address of an int variable. This is for type safety and correct memory interpretation.

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

What is dynamic memory allocation in C++, and which operator is used to allocate memory dynamically?

A

Dynamic memory allocation is the process of allocating memory at runtime rather than compile time. The new operator is used for this, e.g., p_int = new int;.

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

Which operator is used to de-allocate memory that was dynamically allocated with new? Why is this important?

A

The delete operator is used, e.g., delete p_int;. It’s crucial to de-allocate memory to prevent memory leaks, where memory is consumed but no longer accessible or usable by the program.

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

If you allocate an array dynamically using p_arr = new int[10];, how must you de-allocate it?

A

You must use delete[] p_arr;. Using delete p_arr; for an array allocated with new[] results in undefined behavior (typically only the first element is freed, leading to a memory leak).

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

What is a ‘dangling pointer’? How can it occur after using delete?

A

A dangling pointer is a pointer that points to a memory location that has been de-allocated (freed). It can occur if you delete the memory a pointer points to, but the pointer variable itself still holds that (now invalid) address.

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

What is nullptr (or NULL in older C/C++), and why is it good practice to assign it to a pointer after deleteing the memory it pointed to?

A

nullptr is a special keyword representing a pointer that doesn’t point to any valid memory location. Assigning ptr = nullptr; after delete ptr; helps prevent the accidental use of a dangling pointer, as you can check if (ptr != nullptr) before dereferencing.

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

Explain a ‘pointer to a constant variable’ (e.g., const int *ptr;). What can and cannot be done through such a pointer?

A

ptr points to an integer that is treated as constant through this pointer. You cannot change the value of the integer using *ptr. However, ptr itself can be reassigned to point to a different const int (or even a non-const int, which will then be treated as const through ptr).

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

Explain a ‘constant pointer’ (e.g., int *const ptr = &var;). What can and cannot be done with such a pointer?

A

ptr is a pointer whose own value (the address it stores) cannot be changed after initialization; it must always point to the same memory location. However, the value at that memory location (if var is not const) can be changed using *ptr.

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

Explain a ‘constant pointer to a constant variable’ (e.g., const int *const ptr = &var;).

A

ptr must always point to the same memory location, AND the integer value at that location cannot be changed through *ptr.

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

What is a ‘reference variable’ in C++? How is it declared and initialized?

A

A reference variable is an alias or an alternative name for an already existing variable. It’s declared using & (e.g., int &ref_num = original_num;). A reference must be initialized at the time of declaration and cannot be ‘reseated’ to refer to a different variable later.

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

What are the main practical differences between pointers and references?

A
  1. References must be initialized upon declaration; pointers do not. 2. References cannot be reassigned to refer to another variable after initialization; pointers can. 3. References always refer to an object (cannot be null); pointers can be nullptr. 4. References use dot (.) to access members of an object (like the object itself); pointers use arrow (->). Dereferencing a pointer (*p) is needed to access the value, while a reference directly acts as the variable.
17
Q

When passing an argument to a function by pointer (e.g., void func(int *p)), what is actually passed to the function? How does this allow modification of the original variable?

A

The memory address of the original variable is passed to the function. Inside the function, by dereferencing the pointer (*p), the function can access and modify the value at that original memory location.

18
Q

When passing an argument to a function by reference (e.g., void func(int &ref)), what is conceptually passed? How does this allow modification of the original variable?

A

The function receives an alias (another name) for the original variable. Any operations on the reference parameter inside the function directly affect the original variable in the caller’s scope.

19
Q

Which method of passing arguments to allow modification of the original variable is generally preferred in modern C++: pass-by-pointer or pass-by-reference, and why?

A

Pass-by-reference is generally preferred in C++ for modifying arguments because the syntax for calling the function is cleaner (no need for & operator) and it avoids the possibility of a null pointer (as references must be initialized).

20
Q

Why is it generally unsafe to return a reference or a pointer to a local variable from a function?

A

Local variables are destroyed when the function exits. Returning a reference or pointer to such a variable results in a ‘dangling’ reference/pointer, which points to invalid memory. Accessing it leads to undefined behavior.

21
Q

What does int **pptr; declare?

A

pptr is declared as a pointer to a pointer to an int. pptr stores the address of another pointer, which in turn stores the address of an integer variable.

22
Q

How do you access the final integer value if pptr is a pointer to a pointer to an int that is properly initialized (e.g., int var = 10; int *ptr = &var; int **pptr = &ptr;)?

A

You would use double dereferencing: **pptr.

23
Q

What is a ‘function pointer’? What does it store?

A

A function pointer stores the memory address of a function. It allows functions to be treated somewhat like variables, e.g., passed as arguments to other functions or stored in data structures.

24
Q

How would you declare a function pointer fn_ptr that can point to a function which takes two int arguments and returns an int?

A

int (*fn_ptr)(int, int); The parentheses around *fn_ptr are crucial.

25
If `int add(int a, int b) { return a + b; }` is a function, how can you assign its address to a compatible function pointer `fn_ptr`?
`fn_ptr = add;` (The `&` is optional for function names, as the name itself decays to a pointer).
26
How do you call a function using a function pointer `fn_ptr` that points to a function like `int add(int, int)` with arguments 5 and 3?
`int result = fn_ptr(5, 3);` (Dereferencing with `(*fn_ptr)(5,3)` is also possible but less common for calls).
27
What is a key requirement when assigning a function to a function pointer regarding their signatures?
The function pointer's signature (return type and parameter types) must exactly match the signature of the function it is intended to point to.
28
In the context of splitting a C++ program into multiple files, what is the primary role of a header (`.h` or `.hpp`) file?
Header files primarily contain *declarations*, such as function prototypes, class definitions, `extern` variable declarations, constant definitions, and `typedefs`. They define the *interface* to a module of code.
29
In the context of splitting a C++ program into multiple files, what is the primary role of a source (`.cpp`) file?
Source files primarily contain *definitions* (implementations), such as function bodies and definitions of global variables. They include the necessary header files for the declarations they use or implement.
30
What is the purpose of `srand((unsigned)time(NULL));` when working with `rand()` for random number generation? Which headers are typically needed?
`rand()` generates pseudo-random numbers starting from a 'seed'. Without changing the seed, `rand()` will produce the same sequence each time the program runs. `srand()` seeds the random number generator. `time(NULL)` provides a different value (current time) each run, making the seed different and thus the sequence of random numbers appear more random. Headers: `` for `srand`/`rand`, `` for `time()`.
31
When passing an `ofstream` object to a function (e.g., `void write_data(ofstream& outfile, ...)`), why is it typically passed by reference?
1. To allow the function to write to the actual file stream object opened in the calling function. 2. To avoid copying the stream object, which can be complex and is often disallowed or undesirable for stream objects.
32
For a problem requiring mapping a user-entered number (e.g., 1-7) to a day of the week and displaying a corresponding schedule, which C++ control structure would be most appropriate and why? (Practice Week3 Q2)
A `switch` statement would be very appropriate as it handles multiple distinct integer cases cleanly. An `if-else if-else` chain could also work. The choice depends on readability for the specific number of cases.
33
To create an application that calculates the volume and surface area of a cube based on user input, how might you structure this using functions, and what parameters would these functions likely take? (Practice Week3 Q3)
You could create functions like `double calculate_volume(double side_length)` and `double calculate_surface_area(double side_length)`. They would take the side length as a `double` and return the calculated `double` value. Input would be handled in `main` or a separate input function.
34
If designing a function to calculate the area of a triangle using Heron's formula (`S = sqrt(p(p-a)(p-b)(p-c))`, where `p` is semi-perimeter), what parameters would the function need and what would it return? Which C++ library is essential? (Practice Week3 Q4)
Parameters: `double side_a`, `double side_b`, `double side_c`. Return type: `double` (for the area). The `` library is essential for the `sqrt()` function.
35
To write a C++ function that compares two integers and returns a character ('>', '<', or '=') representing the comparison, what would be the function signature and the core logic? (Practice Week3 Q5)
Signature: `char compare_integers(int num1, int num2);`. Logic: Use `if-else if-else` statements: `if (num1 > num2) return '>'; else if (num1 < num2) return '<'; else return '=';`.
36
For a function `Profit` calculating deposit returns, with parameters for deposit amount, interest rate, compound period (enum/int), and term, what kind of internal logic would be needed for the 'compound period'? (Practice Week3 Q6)
Conditional logic (likely a `switch` statement based on the compound period parameter, or an `if-else if` chain) would be needed to adjust the interest rate and number of compounding periods based on whether compounding is annual, semi-annual, quarterly, etc., before applying the compound interest formula.