Pointers and memory · core
Arrays, C strings and std::string
An array name turns into a pointer to its first element, which is why sizeof changes inside a function. A C string ends with '\0'; std::string manages its own memory and is what you should use.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- arr[i] means *(arr + i), and p + 1 moves by one element (4 bytes for an int), not one byte. *p + 1 is (*p) + 1; *p++ gives *p and then moves p.
- An array passed to a function turns into a pointer to its first element (decay). Inside
void f(int arr[]), sizeof(arr) is the pointer size (8 on 64-bit), so pass the length too, or use a vector. - A C string is a char array that ends with '\0'.
char a[] = "hello"takes 6 bytes; strlen(a) is 5. Compare C strings with strcmp: == compares addresses. - A string literal is a const char array. Changing it is undefined behaviour and usually crashes. C++11 does not allow
char* b = "hello"(g++ only warns); write const char*. - std::string manages its own memory and knows its size: s.size() is O(1), == compares the text, + joins strings, and s.c_str() gives a C string that ends with '\0'.
- s.find(t) returns the position, or string::npos when t is not found. s.substr(pos, len) makes a new copy, so it costs O(len).
- Add a character with s += c or s.push_back(c) (amortised O(1)).
s = s + cin a loop builds a new string every time: O(n^2) in total. - Reverse in place with two indexes: i from the start, j from the end, swap and move inward while i < j. O(n) time, O(1) extra space; empty and one-letter strings need no special case. std::reverse does the same when library functions are allowed.
The red pen
Common traps: mistake → fix
Mistake: sizeof(arr) inside a function gives the array length
Fix: it gives the pointer size.
Mistake: == compares two C strings by their text
Fix: it compares addresses; use strcmp, or use std::string.
Mistake: sizeof("hello") is 5
Fix: it is 6, with the ending '\0'.
Mistake: s = s + c is as fast as s += c
Fix: it copies the whole string each time.
Easy to hard
Questions interviewers ask, easy to hard
- What does this pointer code print? (*p + 1, *(p + 1) and *p++ on an int array)
- Why does sizeof give 8 inside a function that takes an array?
- Why does changing a string literal crash? How should the pointer be declared?
- What is the difference between a C string and std::string?
- Reverse a string in place without library functions. What are the time and space costs?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.