LearnFrenzy
Sign in Take a free test

C Library Functions · Predict the Output · Question 12

strncpy with a short source pads with zeros Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following C program?

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

int main(void) {
    char d[6] = "XXXXX";
    strncpy(d, "ab", 4);
    printf("%s %d %d %c\n", d, d[2], d[3], d[4]);
    return 0;
}
  • A ab 0 0 X Correct
  • B abXXX 88 88 X
  • C ab 0 88 X
  • D ab 0 0 0
Correct Answer: Option A

strncpy copies "ab" and then fills the rest of the first n = 4 bytes with '\0'; byte 4 is untouched. When the source is longer than n, no terminator is written at all.

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