I'm trying to copy string s
to r
using strcpy()
. But it does not print out any result. Why?
#include <iostream>
using namespace std;
#include <string.h>
int main() {
char s[] = "john lemon";
char r[] = "";
strcpy(s, r);
cout<<s<<" "<<r;
return 0;
}
CodePudding user response:
strcpy(a,b)
copies the string b
into the string a
You have copied the empty string to the the string s
. After the copy it also contains the empty string.
Printing empty string results with no characters outputted as empty string does not contain any printable ones.
If you want to copy in the opposite direction you must make sure that the destination array has enough elements to accommodate the source string.
char s[] = "john lemon";
char r[sizeof(s)] = "";
strcpy(r, s);
CodePudding user response:
The first parameter of strcpy(char* dest, char* src)
is the destination string where the content is to be copied, while the second one is the source string to be copied. Be aware that it is important to reserve enough space for the parameter dest
to receive the content.
So try this please:
#include <iostream>
using namespace std;
#include <string.h>
int main() {
char s[] = "john lemon";
char r[20];
strcpy(r, s);
cout<<s<<" "<<r;
return 0;
}