OA. free
Free
Texas Instruments Embedded Systems & Hardware Embedded Systems & Hardware Medium

12.

Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Working with arrays**

Predict the output of the following C code snippet.

bool compare (const void * a, const void * b)
{
    return (*(int*)a == *(int*)b);  //L1
}

int search(void *arr, int arr_size, int ele_size, void *x,
           int (*compare)(const void *, const void *)) //L2
{
    char *ptr = (char *)arr;
    int i;
    for (i=0; i<arr_size; i++)
        if (compare(ptr + i*ele_size, x)) //L3
            return i;
    return -1;
}

int main()
{
    int arr[] = {2, 5, 7, 80, 70};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 7;
    printf ("The index is %d ", search(arr, n, sizeof(int), &x, compare));
    return 0;
}
Choose one option.
Show answer & explanation
Answer: A. A) The index is 2

The code implements a generic linear search. The 'search' function iterates through the array using byte-offset pointer arithmetic and uses a callback function 'compare' to check for equality between the current element and the target value.

Step-by-step Derivation:
Step 1: Analyze the 'compare' function. It takes two void pointers, casts them to int pointers, dereferences them, and returns true (1) if the values are equal and false (0) otherwise.
Step 2: Analyze the 'search' function. It takes the array base address, size, element size, target value pointer, and the comparison function. It uses a char pointer (ptr) to perform byte-level arithmetic: 'ptr + i * ele_size' correctly calculates the address of the i-th element of any type.
Step 3: Trace the 'main' function.

  • arr = {2, 5, 7, 80, 70}, n = 5, x = 7.
  • i = 0: compare(&arr[0], &x) -> (2 == 7) is false.
  • i = 1: compare(&arr[1], &x) -> (5 == 7) is false.
  • i = 2: compare(&arr[2], &x) -> (7 == 7) is true. Returns i = 2.
    Step 4: The printf statement outputs 'The index is 2'. Note: While there is a type mismatch in the function pointer declaration for 'compare' (bool vs int), in standard C, bool is often treated as an integer, and this will compile and execute correctly in most environments.