strlen against sizeof — Aptitude Question
strlen against sizeof: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What does this C program print?
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "PLACEMENT";
printf("%d %d", (int) strlen(s), (int) sizeof(s));
return 0;
}Options
- 9 9
- 9 10
- 10 9
- 10 10
Show the answer and the worked solution
Correct answer: B. 9 10
Worked solution
- PLACEMENT has 9 letters, and strlen counts characters up to but not including the terminator, so it returns 9.
- The array s is sized to hold those 9 characters plus the terminating null, so it occupies 10 chars.
- sizeof(s) is therefore 10 and the program prints 9 10.
Answer: 9 10.
The idea
strlen is a runtime scan for the null terminator; sizeof is a compile-time count of the storage. They differ by exactly one for a char array initialised from a literal.
Shortcut. For an array initialised from a literal, sizeof can never be less than strlen + 1, which leaves only "9 10" once PLACEMENT is counted as 9 letters.
Common trap. "9 9" forgets the terminating null character that the literal adds to the array's storage.
All Programming Fundamentals questions · placement mock tests