C and C++ Guide: Pointers, Memory, OOP, STL and Interview Questions
Updated 28 Oct 2026 7 min read
On this page 13 sections
- 1Why learn C and C++
- 2The shape of a C program and the build process
- 3Data types, sizes and operators
- 4Pointers: the heart of C
- 5Arrays and strings
- 6Memory layout and dynamic allocation
- 7Structures, unions, enums and bit manipulation
- 8Files, recursion and the standard library
- 9From C to C++
- 10Modern C++ topics that impress
- 11Frequently asked interview questions
- 12Programs to practise without an IDE
- 13Practice plan
Why learn C and C++
C and C++ are close to the hardware. They power operating systems, embedded devices, game engines, databases, browsers and performance-critical software, and they are common in college syllabi and placement tests. Learning them teaches you how memory and the machine really work, which makes you better in every other language. They are essential for embedded roles and valuable for systems work. C++ is also a favourite for competitive programming because of the speed and convenience of the STL (DSA plan).
Interviews on these languages test memory understanding more than syntax. If you can explain what happens to a variable in memory, you can answer most questions.
1. The shape of a C program and the build process
#include <stdio.h>
int main(void) {
int a = 7, b = 3;
printf("Sum = %d\n", a + b);
return 0;
}
Compile with gcc hello.c -o hello and run ./hello. The build has four stages: preprocessing (handles #include and #define), compilation (to assembly), assembly (to object code) and linking (combining object files and libraries into an executable). Know the difference between a declaration and a definition, and between header files and source files. Always compile with warnings on: gcc -Wall -Wextra -g.
2. Data types, sizes and operators
- Common types:
char(1 byte),int(usually 4),float(4),double(8),long,long long. Usesizeofto check. signedvsunsigned: overflow of unsigned wraps around; signed overflow is undefined behaviour- Integer division:
5 / 2is 2;5 / 2.0is 2.5 ==vs=mistakes, operator precedence, and the difference betweeni++and++i- Undefined behaviour (reading uninitialised variables, out-of-bounds access, signed overflow, dereferencing NULL) can appear to work and then fail; interviewers like candidates who know this
const,static(a local keeps its value between calls; a global is private to its file) andvolatile(the value can change outside the program's control, such as a hardware register)typedef,enumand the preprocessor: macros vsconstvsinline, and the classic macro trap#define SQUARE(x) x*x(use parentheses, or an inline function)
3. Pointers: the heart of C
A pointer stores the memory address of another variable.
int x = 10;
int *p = &x; // p holds the address of x
*p = 20; // change x through the pointer
printf("%d %p\n", x, (void *)p);
&xis "address of x";*pis "the value at the address in p"- C passes arguments by value, so pointers are how a function changes the caller's data
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
Pointer arithmetic: p + 1 moves by sizeof(*p) bytes, not one byte. An array name usually decays to a pointer to its first element, so arr[i] equals *(arr + i).
int arr[] = {10, 20, 30};
int *p = arr;
printf("%d %d\n", *(p + 1), p[2]); // 20 30
printf("%zu\n", sizeof(arr)); // 12 (whole array)
// inside a function that receives an int*, sizeof is the pointer size, not the array!
Know these variations: null pointer, void pointer (needs a cast), dangling pointer (points to freed or out-of-scope memory), wild pointer (uninitialised), pointer to pointer (int **pp), function pointers (int (*op)(int, int)), const int *p (data is constant) vs int *const p (the pointer is constant), and why returning the address of a local variable is a bug.
int (*op)(int, int) = add; // function pointer
printf("%d\n", op(2, 3));
4. Arrays and strings
A C string is an array of char ending with the null character '\0'.
char name[] = "Asha"; // 5 bytes including '\0'
char *msg = "hello"; // points to a read-only literal: do not modify it
printf("%zu %zu\n", strlen(name), sizeof(name)); // 4 5
Know strlen, strcpy, strcmp, strcat, strstr, and why unchecked copies cause buffer overflows (a major security problem). Prefer bounded versions (snprintf, strncpy with care) and always leave room for the terminator. Classic programs: reverse a string in place, palindrome check, count vowels, implement strlen and strcpy, anagram check.
void reverse(char *s) {
int i = 0, j = (int)strlen(s) - 1;
while (i < j) {
char t = s[i]; s[i] = s[j]; s[j] = t;
i++; j--;
}
}
Multi-dimensional arrays are stored row by row (row-major), and a 2D array is not the same as an array of pointers.
5. Memory layout and dynamic allocation
A running program's memory has these regions:
- Code (text): the instructions
- Data / BSS: global and static variables (initialised and zero-initialised)
- Heap: memory you request at run time; grows upward
- Stack: local variables and function call frames; grows downward, cleaned up automatically
int *arr = malloc(5 * sizeof(int));
if (arr == NULL) { perror("malloc"); return 1; }
for (int i = 0; i < 5; i++) arr[i] = i * i;
arr = realloc(arr, 10 * sizeof(int)); // use a temp pointer in real code!
free(arr);
arr = NULL; // avoid a dangling pointer
Know the difference between malloc (uninitialised), calloc (zeroed) and realloc (resize), and these errors:
- Memory leak: allocated, never freed
- Double free and use after free
- Buffer overflow and stack overflow (infinite or very deep recursion, huge local arrays)
- Segmentation fault: access to memory you may not touch
Use Valgrind or AddressSanitizer (-fsanitize=address) to catch these.
6. Structures, unions, enums and bit manipulation
struct Student {
int id;
char name[20];
float cgpa;
};
struct Student s = {1, "Ravi", 8.4f};
struct Student *ps = &s;
printf("%d %s\n", ps->id, ps->name); // -> accesses a member through a pointer
- Structure padding: the compiler adds padding for alignment, so
sizeofa struct can exceed the sum of its fields; ordering fields from largest to smallest reduces waste - Union: members share the same memory; size equals the largest member
- Bit fields and endianness (byte order) come up in embedded interviews
n |= (1u << k); // set bit k
n &= ~(1u << k); // clear bit k
n ^= (1u << k); // toggle bit k
int bit = (n >> k) & 1; // read bit k
int pow2 = n > 0 && (n & (n - 1)) == 0; // power of two
int count_bits(unsigned n) { // Brian Kernighan's algorithm
int c = 0;
while (n) { n &= n - 1; c++; }
return c;
}
7. Files, recursion and the standard library
Know fopen, fgets, fprintf, fclose and checking for failure. Recursion needs a base case and uses the stack; know factorial, Fibonacci, tower of Hanoi and why deep recursion can overflow the stack. Know qsort with a comparator function, memcpy vs memmove and atoi/strtol.
8. From C to C++
C++ adds object-oriented and generic features on top of C:
- References:
int &r = x;an alias that cannot be null or reseated - Function overloading, default arguments, namespaces,
inlineandconstexpr newanddeleteinstead ofmallocandfree(constructors and destructors run); usenew[]withdelete[]string,vectorand the rest of the STL instead of raw arrays andchar *
OOP in C++
class Animal {
public:
virtual ~Animal() = default; // virtual destructor!
virtual std::string sound() const = 0; // pure virtual: abstract class
};
class Dog : public Animal {
public:
std::string sound() const override { return "woof"; }
};
std::unique_ptr<Animal> a = std::make_unique<Dog>();
std::cout << a->sound();
- Constructors and destructors, copy constructor, copy assignment, move semantics
- Rule of three / five / zero: if you define a destructor, copy operations or move operations, you probably need to define the others; better, use RAII types so you need none
- Virtual functions and the vtable: each polymorphic object has a hidden pointer to a table of function addresses, used for run-time dispatch. A base class with virtual functions needs a virtual destructor, or deleting through a base pointer is undefined behaviour.
- Access:
public,protected,private;structdefaults to public andclassto private - Static members, friend functions, operator overloading, templates (generic code) and exceptions (
try,catch,throw) - Object slicing: copying a derived object into a base object by value loses the derived part
RAII and smart pointers
RAII (resource acquisition is initialisation) ties a resource's lifetime to an object, so cleanup happens automatically even on exceptions. Modern C++ uses std::unique_ptr (sole owner), std::shared_ptr (shared ownership with reference counting) and std::weak_ptr (breaks cycles) instead of raw new and delete.
The STL
#include <bits/stdc++.h> // convenient in contests; use specific headers in real code
using namespace std;
int main() {
vector<int> v = {5, 2, 9, 1};
sort(v.begin(), v.end()); // O(n log n)
unordered_map<string, int> freq;
for (string w : {"a", "b", "a"}) freq[w]++;
priority_queue<int, vector<int>, greater<int>> minHeap;
minHeap.push(3); minHeap.push(1);
cout << minHeap.top() << "\n"; // 1
}
Know containers (vector, deque, list, set, map, unordered_map, stack, queue, priority_queue), iterators, algorithms (sort, lower_bound, reverse, accumulate, next_permutation), lambdas and when each container is the right choice. map is a balanced tree (O(log n), sorted), unordered_map is a hash table (O(1) average).
9. Modern C++ topics that impress
auto, range-based for loops, nullptr (instead of NULL), move semantics and std::move, override and final, std::optional, std::string_view, lambdas, and basic multithreading (std::thread, std::mutex, std::atomic).
10. Frequently asked interview questions
- Difference between a pointer and a reference
- Stack vs heap; what is stored where?
- What is a memory leak, a dangling pointer and a segmentation fault?
mallocvscallocvsnew;freevsdelete- What does
staticdo for a local variable, a global and a class member? - What is
constcorrectness?const int *pvsint *const p - What is a virtual function? Why a virtual destructor?
- What is the vtable?
- Explain the rule of three and five
- What is RAII? What are smart pointers?
- Struct vs class; struct vs union
- What is structure padding?
- What is undefined behaviour? Give examples
vectorvslistvsdeque;mapvsunordered_map- What is a deep copy vs a shallow copy of an object with a pointer member?
11. Programs to practise without an IDE
Reverse a string and a linked list, detect a cycle, swap without a temporary variable, implement strlen, strcpy and memcpy, check endianness, count set bits, find a missing number, implement a stack and queue with arrays and with linked lists, write your own vector-like class with a destructor and copy constructor, and implement a simple smart pointer.
12. Practice plan
- Weeks 1-2: syntax, control flow, arrays, strings, functions; 30 small programs, compiled with
-Wall -Wextra - Weeks 3-4: pointers, dynamic memory, structures, file I/O; linked list, stack and queue from scratch; run Valgrind or AddressSanitizer
- Weeks 5-6: C++ classes, inheritance, virtual functions, templates and STL; solve 40 DSA problems in C++
- Weeks 7-8: smart pointers, move semantics, multithreading basics, mock interviews on the questions above
Pair this with the operating systems guide and the core CS subjects guide, and see OOP and design principles for design questions.
Found this useful? Share it with a friend.