S
S
savole2014-10-14 22:27:40
C++ / C#
savole, 2014-10-14 22:27:40

What will be displayed on the screen after executing this program fragment?

Hello, thanks in advance. I have such a problem, could you explain to me what will be displayed on the screen after executing this program fragment:
char s1[]="word";
scar *s2=new char[5];
strncpy(s2,s1,3);
puts(s2);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2014-10-14
@savole

Three "slo" characters will be output, and possibly something after them, which is unpredictable.
Because strncpy copies no more than n (3) characters from the source string (s1) to the destination string (s2), and if the source string is longer than 3 characters, strncpy does not add a closing character with code 0. Therefore, "layer" will fall into s2, and then the garbage that was in memory will remain, and puts will print all this garbage up to the first character with code 0.

V
Vadim Misbakh-Soloviev, 2014-10-15
@mva

Disagree with the previous speaker.
Because the output depends on the "input" :) That is, on the encoding in which the word "word" is written in the source code. Because if it is a two-byte encoding (unicode), then only three BYTES (and not characters) will be copied (and therefore output). So it will be "s" and half of "l" (which will turn into a replacement character) :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question