Given two C-strings defined as char* s1 and char* s2, the statement s1 = s2; compiles without error. So, copying a C-string with the assignment operator appears straightforward. However, when used with pointer operands, including C-strings, the assignment operator copies the address in the right-hand operand to the left-hand operand - see Figure 1(b), which illustrates pointer assignment. Specifically, the assignment operator does not copy the string text to which the pointer points. Copying a string is still a necessary operation, and so the C-string library provides a function to perform the task: strcpy(s1, s2);.
strcpy: String-Copy
strcpy(s1, s2)
#include <cstring>char* strcpy(char* destination, const char* source);errno_t strcpy_s(char* dest, size_t size, const char* source);
char* s1; char s2[15] = "Hello world"; strcpy(s1, s2); |
char s1[5]; char s2[15] = "Hello world"; strcpy(s1, s2); |
| (a) | (b) |
char* does not allocate memory to store the copied C-string.strcpy function does not require s1 to be null-terminated before the copy operation.
| Standard Version | Microsoft Version |
|---|---|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100] = "EXAMPLE";
char* s2 = "HELLO";
cout << strcpy(s1, s2) << endl;
cout << s1 << endl;
return 0;
}
|
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char s1[100] = "EXAMPLE";
char* s2 = "HELLO";
cout << strcpy_s(s1, 100, s2) << endl;
cout << s1 << endl;
return 0;
}
|
| Output: | |
HELLO HELLO |
0 HELLO |
| (a) | (b) |
char* strcpy(char* dest, const char* source)
{
for (size_t i = 0; i <= strlen(source); i++)
dest[i] = source[i];
return dest;
}
|
char* strcpy(char* dest, const char* source)
{
char* s = dest; // (i)
while (*(s++) = *(source++)) // (ii)
;
return dest; // (iii)
}
|
| (a) | (b) |
<= rather than < - the additional iteration copies the null terminator at the end of source to dest.return statement is common to all strcpy implementations, neither improving nor degrading efficiency.