3. What will be the output of the following Rust code implementing a stack push operation?
let mut stack: [i32; 3] = [0; 3];
let mut top = -1;
// Push function
fn push(stack: &mut [i32; 3], top: &mut i32, value: i32) {
if *top < 2 {
*top += 1;
stack[*top as usize] = value;
}
}
push(&mut stack, &mut top, 10);
push(&mut stack, &mut top, 20);
println!("{:?}", stack);
medium
A. [20, 10, 0]
B. [0, 10, 20]
C. [10, 20, 0]
D. [0, 0, 0]
Solution
Step 1: Trace push calls and stack changes
Initially, stack = [0, 0, 0], top = -1.
First push: top becomes 0, stack[0] = 10 -> [10, 0, 0].
Second push: top becomes 1, stack[1] = 20 -> [10, 20, 0].
Step 2: Print final stack state
Printing stack shows [10, 20, 0].
Final Answer:
[10, 20, 0] -> Option C
Quick Check:
Push adds at top index, stack = [10, 20, 0] [OK]
Hint: Track top index and update array at that position [OK]
Common Mistakes:
Not updating top index before assignment
Confusing array indices order
Assuming push adds at end regardless of top
4. Identify the error in this Rust stack pop function and select the correct fix:
fn pop(stack: &[i32; 3], top: &mut i32) -> Option<i32> {
if *top >= 0 {
let val = stack[*top as usize];
*top -= 1;
Some(val)
} else {
None
}
}
medium
A. Change stack parameter to mutable: &mut [i32; 3]
B. Remove top parameter and use global variable
C. Change return type to i32 instead of Option<i32>
D. No error, function is correct
Solution
Step 1: Analyze the pop function code
The function takes an immutable reference to the stack (&[i32; 3]) and a mutable reference to top. It only reads from the stack at index *top and decrements top.
Step 2: Verify compilation and logic
No writes to the stack array occur, so an immutable reference is sufficient and correct. The function handles empty stack with None and returns the popped value properly.
Final Answer:
No error, function is correct -> Option D
Quick Check:
Immutable stack reference OK for read-only access in pop [OK]
Hint: Pop reads stack immutably and mutates top separately; no stack mutation needed [OK]
Common Mistakes:
Assuming stack must be mutable for pop operations
Suggesting unnecessary global variables
Incorrectly changing return type from Option<i32>
5. Given a fixed-size stack implemented using an array of size 4, which sequence of operations will cause a stack overflow error?