Home / Blog / Programming / C
Top 50 C Interview Questions with Answers
Programming · C · 24 min read
Fifty C interview questions with answers and programs compiled and run on gcc: basics, pointers, memory, strings, structs, and files.
How this sheet works
This sheet holds fifty interview questions about C, grouped by topic. Basics come first. Pointers and memory sit in the middle. Strings, structs, files, and short coding tasks close the sheet.
Every program on this page was compiled with gcc 13.3.0 and run, and the output shown is the output the run produced. Nothing here is a guess at what a program might print.
Cover the answer, say yours out loud, then compare. Type each program in and run it yourself. Saying an answer from memory proves more than recognising it on the page.
The C Beginner course here holds 50 lessons. Answers point at the C lesson that covers the idea, so a miss tells you exactly where to study next.
Two honest limits. Function pointers get a full answer here, but the C course has no lesson on them yet. Linked lists, unions, and threads are missing from both the course and this sheet, so this sheet will not prepare you for questions on those.
1. What is C, and what is it used for?
C is a programming language that sits close to the machine. Programmers write operating systems in it. They write device drivers in it. They write game engines in it, and the small programs inside gadgets and appliances.
C is small. The whole language has only a few dozen keywords. That small size is part of its speed. There is little between your code and the hardware.
C is also old. It dates from the early 1970s, and it still runs the systems the world depends on. The C Introduction lesson opens the Beginner course with a first program.
2. How do you compile and run a C program?
C is a compiled language. You write the code in a file, a compiler turns it into a program, and then you run that program. Python hides the middle step. C shows it to you.
Save the code as main.c. Compile it with this command: gcc main.c -o main. That command builds a program called main from main.c. Run it with ./main on Linux and macOS.
The program below prints one line. The C Get Started lesson covers installing gcc and running this first build.
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
Output:
Hello, world!3. What does #include <stdio.h> do?
It pulls in the standard input-output tools before your code is compiled. stdio stands for standard input-output. printf and putchar live in that toolbox.
Without the line, the compiler does not know printf. It stops with an error. With the line, printf is ready to use.
The program below prints with printf and putchar. The C Syntax lesson shows where the include line sits in a program.
#include <stdio.h>
int main() {
printf("Hello");
putchar('!');
putchar('\n');
return 0;
}
Output:
Hello!4. What is the difference between int, float, double, and char?
They are four kinds of value. int holds whole numbers. float holds numbers with a decimal point. double holds the same kind of number with more precision. char holds one character.
Size is the visible difference. On this machine an int takes 4 bytes, a float takes 4, a double takes 8, and a char takes 1. The program below prints those sizes with sizeof.
Choose by need. Use int for counting. Use double when decimals must stay accurate. Use char for single letters. The C Data Types lesson lists every type with its range.
#include <stdio.h>
int main() {
printf("int: %zu bytes\n", sizeof(int));
printf("float: %zu bytes\n", sizeof(float));
printf("double: %zu bytes\n", sizeof(double));
printf("char: %zu byte\n", sizeof(char));
return 0;
}
Output:
int: 4 bytes
float: 4 bytes
double: 8 bytes
char: 1 byte5. What happens when you divide two integers?
You get an integer back, and the remainder is thrown away. 7 divided by 2 gives 3, not 3.5. C does not round. It cuts.
To keep the decimal part, make one side a decimal number. 7.0 divided by 2 gives 3.5. The % operator gives the remainder instead: 7 % 2 is 1.
The C Operators lesson works through division and remainder with more cases.
#include <stdio.h>
int main() {
printf("7 / 2 = %d\n", 7 / 2);
printf("7.0 / 2 = %f\n", 7.0 / 2);
printf("7 %% 2 = %d\n", 7 % 2);
return 0;
}
Output:
7 / 2 = 3
7.0 / 2 = 3.500000
7 % 2 = 16. What is the difference between = and ==?
The single equals stores a value. The double equals asks a question. x = 5 puts 5 into x. x == 5 asks whether x already holds 5.
Mixing them up is the classic beginner bug. Writing if (x = 5) stores 5 and the test always passes. Writing if (x == 5) tests the value and leaves it alone.
The program below prints both results. The C Comparison Operators lesson covers the full set of tests.
#include <stdio.h>
int main() {
int x = 3;
printf("x == 5 is %d\n", x == 5);
printf("x = 5 is %d\n", x = 5);
printf("x is now %d\n", x);
return 0;
}
Output:
x == 5 is 0
x = 5 is 5
x is now 57. What is the difference between ++i and i++?
Both add one. They differ in what they hand back. ++i adds one and hands back the new value. i++ hands back the old value and adds one afterwards.
Alone on a line, they do the same thing. Inside a bigger expression, they do not. That is the whole trap.
The program below prints both. The C Operators lesson shows the same two moves in context.
#include <stdio.h>
int main() {
int a = 5;
int b = 5;
printf("++a is %d\n", ++a);
printf("b++ is %d\n", b++);
printf("b is now %d\n", b);
return 0;
}
Output:
++a is 6
b++ is 5
b is now 68. What does the ternary operator do?
It is a short if-else that gives back a value. The shape is condition ? value-if-true : value-if-false. A score of 72 or more gives Pass. Anything lower gives Fail.
Use it for one small choice. Chain it and the line turns hard to read. Two levels is the most a reader can follow at a glance.
The C Ternary Operator lesson works through the same pattern with a second example.
#include <stdio.h>
int main() {
int score = 72;
printf("%s\n", score >= 50 ? "Pass" : "Fail");
printf("%s\n", 95 >= 90 ? "Top marks" : "Pass");
return 0;
}
Output:
Pass
Top marks9. How does a switch statement differ from if-else?
A switch tests one value against many fixed labels. An if-else chain can test anything, including ranges. A switch suits a short list of exact matches.
Each label is a case. Without break, the program falls through into the next case. That fall-through is a feature when two labels share one result, and a bug when it is an accident.
The program below groups Saturday and Sunday together. The C Switch lesson covers the same grouping.
#include <stdio.h>
int main() {
int day = 6;
switch (day) {
case 6:
case 7:
printf("Weekend\n");
break;
default:
printf("Weekday\n");
break;
}
return 0;
}
Output:
Weekend10. What is the difference between while and do-while?
A while loop tests first and runs second. If the test fails at once, the body never runs. A do-while loop runs first and tests second. Its body runs at least once.
Use while when the work may not be needed at all. Use do-while when the work must happen once before any test makes sense.
The program below runs both with a count of zero. Only the do-while body prints. The C Do While Loop lesson shows the same contrast.
#include <stdio.h>
int main() {
int count = 0;
while (count > 0) {
printf("while body\n");
count--;
}
do {
printf("do-while body\n");
} while (count > 0);
printf("Done\n");
return 0;
}
Output:
do-while body
Done11. What is a variable's scope in C?
Scope is where a name can be used. A variable declared inside braces belongs to those braces. Outside them, the name means nothing.
An inner block can declare its own variable with the same name. Inside the block, the inner one wins. Outside, the outer one is back.
The program below prints 2 inside and 1 outside. The C Scope lesson works through shadowing with functions as well.
#include <stdio.h>
int main() {
int value = 1;
{
int value = 2;
printf("Inside: %d\n", value);
}
printf("Outside: %d\n", value);
return 0;
}
Output:
Inside: 2
Outside: 112. What is the difference between a global and a local variable?
A global variable is declared outside every function. Any function in the file can read it and change it. A local variable is declared inside a function. Only that function can see it.
Globals are shared, and shared means risky. Any function can change a global, so a wrong value is hard to trace. Locals stay private to one function, so a bug in one function cannot reach them.
The program below prints both. The C Scope lesson explains when a global is worth the risk.
#include <stdio.h>
int total = 10;
void show_total() {
printf("Global total: %d\n", total);
}
int main() {
int total = 3;
printf("Local total: %d\n", total);
show_total();
return 0;
}
Output:
Local total: 3
Global total: 1013. What does static do inside a function?
A normal local variable is born when the function runs and dies when it returns. A static local variable is born once and keeps its value between calls.
The first call sets it to zero and counts up to one. The second call finds it still at one and counts to two. Nothing outside the function can touch it.
The program below calls the counter three times. The C Storage Classes lesson covers static at file level too.
#include <stdio.h>
int next_id() {
static int id = 0;
id++;
return id;
}
int main() {
printf("%d\n", next_id());
printf("%d\n", next_id());
printf("%d\n", next_id());
return 0;
}
Output:
1
2
314. What is the difference between a function declaration and a definition?
A declaration tells the compiler a function exists. It gives the name, the inputs, and the output. It has no body. A definition gives the body as well.
Put the declaration before main and the definition after it. The compiler then trusts the call in main, and the definition keeps its promise later.
The program below doubles 21. The C Function Declaration lesson shows the same split.
#include <stdio.h>
int double_it(int n);
int main() {
printf("%d\n", double_it(21));
return 0;
}
int double_it(int n) {
return n * 2;
}
Output:
4215. How do you pass an array to a function?
Pass the array name and its length. The function receives a pointer to the first element, not a copy of the array. It must be told how many elements to read.
The function can change the array, because it holds the address of the real elements. It cannot know the length on its own. sizeof inside the function gives the size of a pointer, not the array.
The program below sums three numbers. The C Function Parameters lesson covers passing single values by copy as well.
#include <stdio.h>
int sum(int numbers[], int count) {
int total = 0;
for (int i = 0; i < count; i++) {
total += numbers[i];
}
return total;
}
int main() {
int scores[] = {4, 8, 15};
printf("Total: %d\n", sum(scores, 3));
return 0;
}
Output:
Total: 2716. What is recursion, and how does it end?
Recursion means a function calls itself. The new call handles a smaller piece of the job. Calls pile up until the smallest piece is reached.
Every recursive function needs a stopping test, called the base case. Factorial stops at 1. Without the test, the calls never end and the program runs out of stack space.
The program below works out 5!. The C Recursion lesson traces the calls one by one.
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("5! = %d\n", factorial(5));
return 0;
}
Output:
5! = 12017. How are arrays stored in memory?
An array is one unbroken block of memory. The elements sit side by side in order. The first element starts the block, and each next element follows at a fixed step.
The step is the size of one element. Four ints take 16 bytes. The program below prints the element count, the size of one int, and the step between neighbours.
That layout is why indexing is fast. The address of element i is the start plus i steps. The C Arrays lesson draws the same block.
#include <stdio.h>
int main() {
int scores[] = {10, 20, 30, 40};
printf("Elements: %zu\n", sizeof(scores) / sizeof(scores[0]));
printf("One int takes %zu bytes\n", sizeof(scores[0]));
printf("scores[1] is %td step after scores[0]\n", &scores[1] - &scores[0]);
printf("Third element: %d\n", scores[2]);
return 0;
}
Output:
Elements: 4
One int takes 4 bytes
scores[1] is 1 step after scores[0]
Third element: 3018. What happens when you read past the end of an array?
You read memory that is not yours. C does not check the index. The value you get is whatever happens to sit there, and it can change from one run to the next.
That is undefined behaviour. The program may print garbage, crash, or seem to work. Seeming to work is the worst outcome, because the bug hides until the worst moment.
The fix is counting. sizeof gives the size of the whole array, and dividing by the size of one element gives the count. The program below loops only to that count. The C Array Size and Loops lesson teaches the same counting trick.
#include <stdio.h>
int main() {
int scores[] = {10, 20, 30, 40, 50};
int count = sizeof(scores) / sizeof(scores[0]);
printf("The array holds %d values\n", count);
for (int i = 0; i < count; i++) {
if (i > 0) {
printf(" ");
}
printf("%d", scores[i]);
}
printf("\n");
return 0;
}
Output:
The array holds 5 values
10 20 30 40 5019. What is the difference between a string and a character array?
A string is a character array that ends with a zero byte. That zero is called the null terminator. It marks where the text stops.
The word hi takes three slots: h, i, and the terminator. strlen counts the letters and stops at the zero, so it reports 2. sizeof counts every slot, so it reports 3.
A character array without the terminator is not a string. Passing it to a string function reads past the end. The C Strings lesson shows the terminator in place.
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "hi";
printf("Length: %zu\n", strlen(word));
printf("Size: %zu\n", sizeof(word));
printf("Last slot: %d\n", word[2]);
return 0;
}
Output:
Length: 2
Size: 3
Last slot: 020. What do strlen, strcpy, strcat, and strcmp do?
They are the four string tools in string.h. strlen counts the letters. strcpy copies one string into another. strcat joins one string onto the end of another. strcmp compares two strings.
strcmp returns zero when the strings match. It returns a negative number when the first string comes earlier, and a positive number when it comes later. Apple comes before Banana, so the program below prints -1.
The copy in the program needs room. The destination holds 20 slots, and Apple pie fits. The C String Functions lesson works through the same four tools with a longer comparison.
#include <stdio.h>
#include <string.h>
int main() {
char first[] = "Apple";
char second[] = "Banana";
printf("Length of Apple: %zu\n", strlen(first));
printf("Apple vs Banana: %d\n", strcmp(first, second));
char copy[20];
strcpy(copy, first);
strcat(copy, " pie");
printf("Copy: %s\n", copy);
return 0;
}
Output:
Length of Apple: 5
Apple vs Banana: -1
Copy: Apple pie21. What is the difference between strcpy and strncpy?
strcpy copies until it meets the terminator. It never asks whether the destination is big enough. strncpy copies at most n characters, and stops there.
That limit is the safety, and it has a catch. When the source is longer than n, strncpy does not add a terminator. The destination is then not a proper string.
The program below copies five letters and adds the terminator by hand. The C String Functions lesson covers the same rule.
#include <stdio.h>
#include <string.h>
int main() {
char dest[6];
strncpy(dest, "Hello, world!", 5);
dest[5] = '\0';
printf("First five: %s\n", dest);
printf("Length: %zu\n", strlen(dest));
return 0;
}
Output:
First five: Hello
Length: 522. What is the difference between strcmp and strncmp?
strcmp compares whole strings. strncmp compares only the first n characters. The limit lets you compare a prefix and ignore the rest.
apple and application share four letters, then part ways at the fifth. Both calls below return the same negative number, because the split happens inside the first five letters.
Use strncmp when only the start matters, such as checking a command word. The C String Functions lesson covers the same pair.
#include <stdio.h>
#include <string.h>
int main() {
printf("apple vs application, 5 chars: %d\n", strncmp("apple", "application", 5));
printf("apple vs application, 6 chars: %d\n", strncmp("apple", "application", 6));
return 0;
}
Output:
apple vs application, 5 chars: -4
apple vs application, 6 chars: -423. What is a pointer?
A pointer is a name for a place in memory. It stores an address. That address names the spot where a value lives. The pointer holds no value of its own kind.
Declare a pointer with a star. int *p means p can hold the address of an int. Assign it with p = &age, and read the value with *p.
The program below changes age through its pointer. The C Pointers lesson introduces the same two moves.
#include <stdio.h>
int main() {
int age = 30;
int *p = &age;
printf("Age through the pointer: %d\n", *p);
*p = 31;
printf("Age after the change: %d\n", age);
return 0;
}
Output:
Age through the pointer: 30
Age after the change: 3124. What is the difference between & and *?
The ampersand gives the address of a variable. The star follows a pointer to the value at that address. They are opposites. The ampersand asks where something lives. The star asks what lives there.
int *p = &age stores the address of age in p. *p then reads the value 30. Change *p and age changes too, because they name the same place.
The program below prints both facts. The C Memory Address lesson shows the same pair.
#include <stdio.h>
int main() {
int age = 30;
int *p = &age;
printf("Pointer holds the address: %d\n", p == &age);
printf("Pointer reads the value: %d\n", *p);
return 0;
}
Output:
Pointer holds the address: 1
Pointer reads the value: 3025. What is a NULL pointer?
A NULL pointer points nowhere. It is the value a pointer holds when it has no address yet. Test for it with p == NULL.
NULL means empty on purpose. It is not zero as a value. It is a marker that says this pointer holds no address.
Reading through a NULL pointer crashes the program. Check first, then read. The program below prints the test before and after the pointer gains an address. The C Pointers lesson covers the same check.
#include <stddef.h>
#include <stdio.h>
int main() {
int *p = NULL;
printf("Pointer is empty: %d\n", p == NULL);
int age = 30;
p = &age;
printf("Pointer is empty: %d\n", p == NULL);
printf("Value: %d\n", *p);
return 0;
}
Output:
Pointer is empty: 1
Pointer is empty: 0
Value: 3026. What is pointer arithmetic?
Adding to a pointer moves it by whole elements, not by bytes. p + 2 on an int pointer moves two ints forward, which is eight bytes. The compiler knows the size.
That is why *(p + 2) and p[2] mean the same thing. Indexing is pointer arithmetic with friendlier spelling.
The program below prints the third value both ways. The C Pointers and Arrays lesson works through the same steps.
#include <stdio.h>
int main() {
int scores[] = {10, 20, 30, 40};
int *p = scores;
printf("Third value by pointer: %d\n", *(p + 2));
printf("Third value by index: %d\n", p[2]);
printf("Steps from first to third: %td\n", (p + 2) - p);
return 0;
}
Output:
Third value by pointer: 30
Third value by index: 30
Steps from first to third: 227. What is the difference between an array name and a pointer?
An array name acts like a pointer to the first element, but it is not a variable. You cannot point it somewhere else. A pointer is a variable, and you can move it.
sizeof shows the difference. sizeof on an array gives the size of the whole block: 20 bytes for five ints. sizeof on a pointer gives the size of one address: 8 bytes here.
The program below prints both sizes. The C Pointers and Arrays lesson explains when the name turns into a pointer.
#include <stdio.h>
int main() {
int scores[] = {10, 20, 30, 40, 50};
int *p = scores;
printf("Size of the array: %zu\n", sizeof(scores));
printf("Size of the pointer: %zu\n", sizeof(p));
printf("First value both ways: %d %d\n", scores[0], *p);
return 0;
}
Output:
Size of the array: 20
Size of the pointer: 8
First value both ways: 10 1028. What is a pointer to a pointer?
It is a pointer that holds the address of another pointer. int **pp means pp points at a pointer, and that pointer points at an int. Two stars mean two steps.
Read it from the right. *pp is the inner pointer. **pp is the int at the end of the chain. Change **pp and the original variable changes.
The program below changes age through two pointers. The C course has no lesson on pointers to pointers, so this answer is self-contained.
#include <stdio.h>
int main() {
int age = 30;
int *p = &age;
int **pp = &p;
printf("Age through two pointers: %d\n", **pp);
**pp = 31;
printf("Age after the change: %d\n", age);
return 0;
}
Output:
Age through two pointers: 30
Age after the change: 3129. What is a void pointer?
A void pointer is a pointer with no type. It can hold the address of anything: an int, a double, a struct. It cannot be read until it is cast back to a real type.
Write void *p. Assign any address to it. Read it with *(int *)p for an int, or *(double *)p for a double. The cast tells the compiler how many bytes to read.
The program below reads both kinds through one pointer. The C course never names void pointers, so this answer is self-contained.
#include <stdio.h>
int main() {
int age = 30;
double price = 2.5;
void *p = &age;
printf("Int through a void pointer: %d\n", *(int *)p);
p = &price;
printf("Double through a void pointer: %f\n", *(double *)p);
return 0;
}
Output:
Int through a void pointer: 30
Double through a void pointer: 2.50000030. What is a function pointer?
A function pointer holds the address of a function. Call through it, and the function runs. The pointer lets the caller choose which function runs.
Declare it with the same shape as the function. int (*op)(int, int) means op can point at a function that takes two ints and returns an int. Assign it with op = add, and call it with op(3, 4).
The program below calls add both ways. The C course has no lesson on function pointers, so this answer is self-contained.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*op)(int, int) = add;
printf("3 + 4 = %d\n", op(3, 4));
printf("3 + 4 = %d\n", (*op)(3, 4));
return 0;
}
Output:
3 + 4 = 7
3 + 4 = 731. What is the difference between the stack and the heap?
The stack holds locals. It grows when a function runs and shrinks when it returns. The heap holds memory you ask for by name, with malloc. It stays until you free it.
Stack memory is automatic. Heap memory is manual. A local disappears on its own. A malloc block stays until free is called, even after the function returns.
The program below holds one value on each. The C Dynamic Memory lesson shows the heap side in full.
#include <stdio.h>
#include <stdlib.h>
int main() {
int local = 7;
int *heap = malloc(sizeof(int));
if (heap == NULL) {
return 1;
}
*heap = 8;
printf("Local value: %d\n", local);
printf("Heap value: %d\n", *heap);
free(heap);
return 0;
}
Output:
Local value: 7
Heap value: 832. What do malloc, calloc, realloc, and free do?
They are the four memory tools in stdlib.h. malloc asks for uninitialised bytes. calloc asks for zeroed memory. realloc grows or shrinks a block. free returns a block.
malloc takes a byte count. calloc takes a count and a size, and fills the block with zeroes. realloc keeps the old contents and may move the block. Always test the result against NULL before using it.
The program below uses all four. The C Dynamic Memory lesson works through the same four calls.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *scores = malloc(3 * sizeof(int));
if (scores == NULL) {
return 1;
}
scores[0] = 10;
scores[1] = 20;
scores[2] = 30;
printf("Three values: %d %d %d\n", scores[0], scores[1], scores[2]);
int *bigger = realloc(scores, 4 * sizeof(int));
if (bigger == NULL) {
free(scores);
return 1;
}
scores = bigger;
scores[3] = 40;
printf("Four values: %d %d %d %d\n", scores[0], scores[1], scores[2], scores[3]);
free(scores);
int *zeros = calloc(3, sizeof(int));
if (zeros == NULL) {
return 1;
}
printf("Calloc values: %d %d %d\n", zeros[0], zeros[1], zeros[2]);
free(zeros);
return 0;
}
Output:
Three values: 10 20 30
Four values: 10 20 30 40
Calloc values: 0 0 033. What is the difference between malloc and calloc?
malloc leaves the memory as it was. calloc fills it with zeroes. That single difference decides which one you reach for.
Use calloc when the values must start at zero. Use malloc when you will fill every slot yourself before reading it. Never read a malloc block before writing to it.
The program below prints five zeroes from calloc. The C Dynamic Memory lesson compares the two calls directly.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *zeros = calloc(5, sizeof(int));
if (zeros == NULL) {
return 1;
}
for (int i = 0; i < 5; i++) {
if (i > 0) {
printf(" ");
}
printf("%d", zeros[i]);
}
printf("\n");
free(zeros);
return 0;
}
Output:
0 0 0 0 034. What is a memory leak?
A leak is memory that was asked for and never returned. Each malloc without a matching free keeps its block. The program slowly holds more and more, and never gives any back.
Small leaks hide. A program that leaks a little on each request can run for weeks before the machine runs short. Long-running programs feel leaks first.
The program below allocates a thousand blocks and frees none. The counts tell the story. The C Dynamic Memory lesson pairs every malloc with its free.
#include <stdio.h>
#include <stdlib.h>
int main() {
int allocated = 0;
int freed = 0;
for (int i = 0; i < 1000; i++) {
int *block = malloc(1024);
if (block == NULL) {
return 1;
}
*block = i;
allocated++;
/* No free(block) here: the block is never returned. */
}
printf("Blocks allocated: %d\n", allocated);
printf("Blocks freed: %d\n", freed);
return 0;
}
Output:
Blocks allocated: 1000
Blocks freed: 035. What is a dangling pointer?
A dangling pointer points at memory that has been freed. The block is gone, but the pointer still holds its old address. Reading through it is undefined behaviour.
The fix is one line. Set the pointer to NULL right after free. A NULL pointer is easy to test. A dangling one looks valid until it crashes.
The program below frees its block and sets the pointer to NULL. The C Dynamic Memory lesson teaches the same habit.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = malloc(sizeof(int));
if (p == NULL) {
return 1;
}
*p = 42;
printf("Value before free: %d\n", *p);
free(p);
p = NULL;
printf("Pointer is empty after free: %d\n", p == NULL);
return 0;
}
Output:
Value before free: 42
Pointer is empty after free: 136. What is a struct, and when would you use one?
A struct groups values of different kinds under one name. A point has an x and a y. A student has a name, an age, and a score. One struct holds all three.
Declare the shape once with struct Point { int x; int y; }. Then make values of that shape. Read a field with a dot: p.x.
The program below prints a point. The C Structures lesson builds bigger structs from the same shape.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p = {3, 4};
printf("Point: (%d, %d)\n", p.x, p.y);
return 0;
}
Output:
Point: (3, 4)37. What is the difference between . and ->?
Both reach a struct field. The dot works on a struct value. The arrow works on a pointer to a struct. p.x reads the field of p. pp->x reads the field through pp.
The arrow is short for two steps. pp->x means (*pp).x: follow the pointer, then read the field. The arrow saves a pair of brackets and a star.
The program below reads both ways and changes y through the pointer. The C Structures lesson covers the same pair.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p = {3, 4};
struct Point *pp = &p;
printf("Through the value: %d\n", p.x);
printf("Through the pointer: %d\n", pp->x);
pp->y = 9;
printf("After the change: (%d, %d)\n", p.x, p.y);
return 0;
}
Output:
Through the value: 3
Through the pointer: 3
After the change: (3, 9)38. What does typedef do?
typedef gives a type a shorter name. struct Point becomes Point. The code reads cleaner, and the struct keyword stops cluttering every declaration.
Write typedef struct { int x; int y; } Point;. After that line, Point is a type like int. Declare values with Point p = {3, 4};.
The program below prints a point declared the short way. The C Typedef lesson shows the same shorthand.
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
int main() {
Point p = {3, 4};
printf("Point: (%d, %d)\n", p.x, p.y);
return 0;
}
Output:
Point: (3, 4)39. What is an enum?
An enum is a list of named numbers. enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }; gives Monday the value 0 and Sunday the value 6. The names make the numbers readable.
An enum fits any value with a short list of meanings. Days, months, and states all fit. A plain int would hold the same numbers, but the names would be lost.
The program below prints four of the values. The C Enums lesson works through the same list.
#include <stdio.h>
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN };
int main() {
enum Day today = WED;
printf("Monday: %d\n", MON);
printf("Wednesday: %d\n", WED);
printf("Today: %d\n", today);
printf("Sunday: %d\n", SUN);
return 0;
}
Output:
Monday: 0
Wednesday: 2
Today: 2
Sunday: 640. What does #define do, and what is a macro?
#define names a piece of text for the preprocessor to swap in. #define PI 3.14 swaps the number in wherever PI appears. The swap happens before the compiler runs.
A macro can take inputs, like a function. #define SQUARE(x) x * x looks safe. It is not. SQUARE(1 + 2) expands to 1 + 2 * 1 + 2, which is 5.
Wrap every input in brackets. #define SQUARE(x) ((x) * (x)) gives 9, the right answer. The program below prints both. The C Preprocessor lesson covers the same trap.
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define BAD_SQUARE(x) x * x
int main() {
printf("Safe square of 1 + 2: %d\n", SQUARE(1 + 2));
printf("Bare square of 1 + 2: %d\n", BAD_SQUARE(1 + 2));
return 0;
}
Output:
Safe square of 1 + 2: 9
Bare square of 1 + 2: 541. What is the difference between #include <...> and #include "..."?
Angle brackets search the system folders first. Use them for standard headers such as stdio.h. Quotes search your own project folders first. Use them for headers you wrote.
The order matters when a name exists in both places. Quotes find your file first, so your version wins. Angle brackets find the system file first.
In practice the rule is simple. System headers take angle brackets. Your headers take quotes. The C Preprocessor lesson shows both forms.
42. What are the bitwise operators, and what is a bitmask?
Bitwise operators work on single bits. & keeps bits that are set in both sides. | keeps bits set in either side. ^ keeps bits set in exactly one side. ~ flips every bit. << shifts left. >> shifts right.
A bitmask is a number used as a set of switches. Each bit stands for one yes-or-no fact. Test one bit with (flags & 4) != 0. The number 5 has bits 0 and 2 set, so bit 2 passes and bit 1 fails.
The program below prints all six operators and two mask tests. The C Bitwise Operators lesson works through the same numbers.
#include <stdio.h>
int main() {
int a = 12; /* 1100 */
int b = 10; /* 1010 */
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
int flags = 5; /* 0101 */
printf("Bit 2 set: %d\n", (flags & 4) != 0);
printf("Bit 1 set: %d\n", (flags & 2) != 0);
return 0;
}
Output:
a & b = 8
a | b = 14
a ^ b = 6
~a = -13
a << 1 = 24
a >> 1 = 6
Bit 2 set: 1
Bit 1 set: 043. What are the storage classes in C?
A storage class says where a variable lives and how long it lasts. There are four: auto, register, static, and extern.
auto is the default for locals: born when the function runs, gone when it returns. register asks the compiler to keep a value in a fast register, and the compiler may ignore the request. static keeps a local alive between calls, or keeps a file-level name private to its file. extern names a variable defined in another file.
Most code uses only two of the four. Locals are auto without saying so. File-level sharing uses static and extern. The C Storage Classes lesson covers all four.
44. How do you read a file in C?
Open it, read it, close it. fopen gives back a FILE pointer. fgets reads one line at a time. fclose returns the file when you are done.
Open for writing with "w" and for reading with "r". Always test the pointer against NULL. A missing file makes fopen return NULL, and reading through NULL crashes.
The program below writes two lines, then reads them back. The C Write to Files and C Read Files lessons cover each half.
#include <stdio.h>
int main() {
FILE *out = fopen("notes.txt", "w");
if (out == NULL) {
return 1;
}
fprintf(out, "First line\n");
fprintf(out, "Second line\n");
fclose(out);
FILE *in = fopen("notes.txt", "r");
if (in == NULL) {
return 1;
}
char line[50];
while (fgets(line, sizeof line, in) != NULL) {
printf("%s", line);
}
fclose(in);
return 0;
}
Output:
First line
Second line45. What is the difference between text mode and binary mode?
Text mode translates line endings. Binary mode does not. On Windows, writing a newline in text mode stores two bytes. In binary mode it stores one. On Linux the two modes are the same.
That is why the same program can behave differently on two machines. Files written in text mode on Windows carry extra bytes. Files written in binary mode are identical everywhere.
The program below writes the same two lines in both modes and prints both sizes. On this Linux machine both are 4. The C Create Files lesson opens files in both modes.
#include <stdio.h>
long file_size(const char *name) {
FILE *f = fopen(name, "rb");
if (f == NULL) {
return -1;
}
fseek(f, 0, SEEK_END);
long size = ftell(f);
fclose(f);
return size;
}
int main() {
FILE *text = fopen("text.txt", "w");
fprintf(text, "a\nb\n");
fclose(text);
FILE *binary = fopen("binary.txt", "wb");
fprintf(binary, "a\nb\n");
fclose(binary);
printf("Text mode size: %ld\n", file_size("text.txt"));
printf("Binary mode size: %ld\n", file_size("binary.txt"));
return 0;
}
Output:
Text mode size: 4
Binary mode size: 446. Why does scanf leave a newline behind?
scanf reads the number and stops. It leaves the newline where it is. The next read finds that newline first, before any real input.
That is the trap. scanf("%d", &age) reads 42 and leaves the newline behind. A fgets straight after reads that newline and returns at once. The name comes back empty.
Eat the newline first. One getchar after scanf clears it. Then fgets reads the real line. The program below reads an age and a name with that fix. The C scanf Traps lesson shows the same trap with more cases.
#include <stdio.h>
#include <string.h>
int main() {
int age;
char name[20];
scanf("%d", &age);
getchar(); /* Eat the newline scanf leaves behind. */
fgets(name, sizeof name, stdin);
name[strcspn(name, "\n")] = '\0';
printf("Age: %d\n", age);
printf("Name: %s\n", name);
return 0;
}
Output:
Age: 42
Name: Maya47. How do you reverse a string?
Swap the ends and walk inward. Swap the first letter with the last. Then the second with the second-last. Stop at the middle.
The loop runs for half the length. Each swap needs one spare slot to hold a letter while the other two change places.
The program below turns hello into olleh. The C Strings lesson covers the string tools this answer builds on.
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "hello";
int len = strlen(word);
for (int i = 0; i < len / 2; i++) {
char tmp = word[i];
word[i] = word[len - 1 - i];
word[len - 1 - i] = tmp;
}
printf("%s\n", word);
return 0;
}
Output:
olleh48. How do you check whether a number is prime?
A prime number has no divisors but 1 and itself. Test every number from 2 upward. Stop at the square root, because a bigger divisor would pair with a smaller one already tested.
The test is one loop. If any number divides evenly, the answer is no. If the loop ends without a hit, the answer is yes. Numbers below 2 are never prime.
The program below tests 29, 30, and 1. The C For Loop lesson covers the loop shape used here.
#include <stdio.h>
int is_prime(int n) {
if (n < 2) {
return 0;
}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
printf("29 is prime: %d\n", is_prime(29));
printf("30 is prime: %d\n", is_prime(30));
printf("1 is prime: %d\n", is_prime(1));
return 0;
}
Output:
29 is prime: 1
30 is prime: 0
1 is prime: 049. How do you find the largest element in an array?
Start by calling the first element the largest. Then walk the rest. Any element bigger than the current largest takes its place.
One pass is enough. The array holds five numbers, and the program below finds 45. The same pass finds the smallest by flipping the test.
The C Arrays lesson covers the same walk with a second example.
#include <stdio.h>
int main() {
int scores[] = {12, 45, 7, 45, 23};
int largest = scores[0];
for (int i = 1; i < 5; i++) {
if (scores[i] > largest) {
largest = scores[i];
}
}
printf("Largest: %d\n", largest);
return 0;
}
Output:
Largest: 4550. Where do I go after this sheet?
Start with the questions you missed, and open the lesson each one names. A miss on pointers means the C Pointers lesson. A miss on memory means the C Dynamic Memory lesson.
Then build the two projects at the end of the C course: the number guessing game and the simple calculator. Each one forces a dozen ideas from this sheet to work together.
One gap stays open. This sheet does not cover linked lists, unions, or threads, because the C course teaches none of them yet. If your interviews ask about those, learn them next, on top of the C here. For most C roles, this sheet and the 50 lessons behind it are enough.
Questions readers ask
How do I use this sheet to prepare in one week?
Work through one topic a day. Cover each answer, say yours out loud, then check it. Run every program yourself. Start with basics and functions, then pointers and memory, then strings and structs, then files and the coding tasks. Return to the questions you missed the next day. Short daily sessions beat one long night of reading.
Do I need to memorise all fifty answers?
No. A few patterns carry the whole sheet: pointers, memory ownership, strings with their terminator, and the array-to-pointer rule. Most questions here are one of those patterns in different clothes. If you can draw a pointer, explain malloc and free, and reverse a string without looking, the rest of the sheet follows from those.
Which C standard should I practise with?
C11, the standard used for every program on this page. Each one was compiled with gcc 13.3.0 using -std=c11. Older standards change little for beginners, but C11 is the safe choice for interviews today.
What is missing from this sheet?
Linked lists, unions, and threads. The C course teaches none of them yet, so this sheet stays silent on them. Function pointers get a full answer here even though the course has no lesson on them. Every other answer here has a lesson behind it on this site.