6. Access Array Element

#include <iostream>
using namespace std;

// Provides direct access to an array element
int& get_element(int arr[], int index) {
    return arr[index];
}

int main() {
    int arr[10];
    for(int i = 0; i < 10; i++) {
        cin >> arr[i];
    }

    int index, value;
    cin >> index >> value;

    &get_element(arr, index);     // valid only if an lvalue is returned

    get_element(arr, index) = value;

    for(int i = 0; i < 10; i++) {
        cout << arr[i] << (i == 9 ? "" : " ");
    }

    return 0;
}

Explanation & Logic Summary:

  •  get_element returns access to an existing array element
  • The returned access supports assignment and address-of operations
  • Updating through the returned access modifies the array directly
  • No temporary objects or copies are created
  • The array outlives all uses of the returned access

Firmware Relevance & Real-World Context:

  • Commonly used in:
    • buffer manipulation
    • memory-mapped register access
    • driver and HAL APIs
  • Enforces:
    • correct lvalue semantics
    • safe reference lifetimes
    • zero-copy data access
  • Evaluates:
    • lvalue vs rvalue understanding
    • API contract deduction
    • embedded-safe C++ design

 

 

 

Loading...

Input

1 2 3 4 5 6 7 8 9 10 3 99

Expected Output

1 2 3 99 5 6 7 8 9 10