AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumcstringssizeof

~75s

strlen against sizeof

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;
}
Show the answer and the worked solution

Correct answer: B.

9 10

Worked solution

  1. PLACEMENT has 9 letters, and strlen counts characters up to but not including the terminator, so it returns 9.
  2. The array s is sized to hold those 9 characters plus the terminating null, so it occupies 10 chars.
  3. 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.

strlen against sizeof — Aptitude Question

strlen against sizeof: What does this C program print? Answer and worked solution on CodeKairo.

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

  1. 9 9
  2. 9 10
  3. 10 9
  4. 10 10
Show the answer and the worked solution

Correct answer: B. 9 10

Worked solution

  1. PLACEMENT has 9 letters, and strlen counts characters up to but not including the terminator, so it returns 9.
  2. The array s is sized to hold those 9 characters plus the terminating null, so it occupies 10 chars.
  3. 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