LearnFrenzy
Sign in Take a free test

Strings · Predict the Output · Question 9

char s[8] = "hi" – sizeof, strlen and the rest Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following C program?

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char s[8] = "hi";
    printf("%zu %zu %d\n", sizeof s, strlen(s), s[5]);
    return 0;
}
  • A 8 2 0 Correct
  • B 3 2 0
  • C 8 2 garbage
  • D 8 8 0
Correct Answer: Option A

The array has the declared size, 8 bytes. The literal fills the first 3 (h, i, \0) and, as with any initializer, the remaining elements are set to 0 – so s[5] is 0, not garbage.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links