bhylu.com

Advertisements

C Interview Questions

Practise explaining array decay, shallow copying and allocation failure with a safe running example.

Your brief

A useful technical discussion asks why an operation is valid, not only which token completes a line. Explain what a function receives when an array is passed, why a structure with a pointer has a shallow copy, and what realloc failure preserves. Then discuss when a linear search is preferable to a hash table and why volatile cannot synchronize a shared counter. These questions connect representation, lifetime and algorithm choices. The worked example below gives a concrete object relationship to explain without depending on undefined behaviour.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror interview-questions.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Worked solution

Show the worked solution
C17 · interview-questions.c

#include <stdio.h>

struct View { int *depth; };

int main(void) {
    int depth = 21;
    struct View first = {&depth};
    struct View second = first;
    *second.depth = 29;
    printf("First sees: %d\n", *first.depth);
    printf("Shared target: %d\n", first.depth == second.depth);
    return 0;
}

Expected result

First sees: 29
Shared target: 1

Copying the structure copies its pointer member, so both views borrow the same live int. Neither view owns a heap allocation and neither should free its target. An owning structure would need a deep-copy or transfer contract to avoid double release. Explain these responsibilities in ordinary language before suggesting a more elaborate implementation.

Extend and test

Describe a deep-copy operation for a record with an allocated name: its input contract, allocation failure policy, output ownership and cleanup responsibilities.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements