#include <iostream>
using namespace std;
void truncate(char* s1, char* s2, int n) {
for (int i = 0; i < n; i ) {
s2[i] = s1[i];
}
}
int main() {
char s1[15] = "Hello World";
char s2[10];
int n{ 5 };
truncate(s1, s2, n);
cout << s2; // this should display: Hello
}
When I run this in Visual Studio, I get this output:
Hello╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Hello World
But when I run it using an online compiler (Online GDB), the output is normal:
Hello
I know it has to do with the \0
terminator but I just can't figure it out.
CodePudding user response:
Your truncate
function doesn't add the required nul
terminator character to the destination (s2
) string. Thus, when you call cout
in main
, that will keep printing characters until it finds its expected nul
(zero) character at some unspecified location following the garbage-initialized data that pre-exists in the parts of the s2
local array that weren't explicitly set by your function. (This is undefined behaviour, and almost anything could actually be displayed; the program may also crash, if the cout
call tries to read memory it doesn't have the required access to).
To correct this, simply add that nul
(zero, or '\0'
) character to the end of the string in the truncate
function. Assuming you don't go beyond the array's bounds, you can use the "left over" value of the loop index, i
, to access the required element; but, to do so, you will need to declare the int i
outside of the for
loop's scope:
void truncate(char* s1, char* s2, int n)
{
int i; // Must be declared outside the FOR loop ...
for (i = 0; i < n; i ) {
s2[i] = s1[i];
}
s2[i] = '\0'; // ... so we can use it here.
}
Note: Another way (but apparently prohibited by your teacher) would be to set all elements of the s2
array in main
to zero, before calling your truncate
function:
char s2[10] = ""; // Set ALL elements to zero
Some compilers (seemingly including the online one you use) will "implicitly" set the elements of uninitialized local arrays to zero; but never rely on this: it is not part of the C Standard and compilers are not required to enforce such behaviour.