STRNCPY overwrites?

Hey there,

In the book it says the following code causes the new value of s to contain “Say Hi”, this string also displays onscreen because it is the value that strncpy() returns.

But rather it looks to me like it overwrites the first 2 chars in s with the first 2 chars in t, hence the y and the space after it showing up in the output.
Is the author of the book that I am reading wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstring>
using namespace std;

int main(void)
{
	char s[7]= "Say ";
	char t[]="Hi";
	cout << strncpy(s, t, 2);
}

/*Output on my computer is:
Hiy Press any key to continue...
*/


The following code I wrote I think will do what the author is trying to do.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstring>
using namespace std;

int main(void)
{
	char s[7]= "Say ";
	char t[]="Hi";
	cout << strcat(s, t);
}

/*Output on my computer is:
Say HiPress any key to continue...
*/
Yes you are right
Just checking, thanks for the info Peter! I can't believe this made it to the presses without being caught :P
You'd be surprised how much bogus/incorrect info gets published.

The thing is... editors are not programmers, so they don't really know whether the code is correct or not.
You probably should use strncat instead of strcat as it's more safe due to having a length check.
Thanks for the tip, I was unaware of that function, since the book didn't mention it.
Topic archived. No new replies allowed.