std::strcpy(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

hiii bestie πŸ’– welcome to the std::strcpy(3) page from the C++ Standard Libary β€” yes, the header spells it like that, and no, we’re not fixing it, it’s iconic πŸ’…. Manual name folded in, vibe check passed, let’s get into the string-copying tea.

✨ NAME ✨

std::strcpy - std::strcpy. Self-titled icon behavior, honestly πŸŽ€.

πŸ¦‹ Synopsis πŸ¦‹

Defined in header <cstring>
char* strcpy( char* dest, const char* src );

So strcpy copies the character string pointed to by src, including the null terminator, into the character array whose first element is pointed to by dest.

The behavior is undefined if the dest array is not large enough. The behavior is undefined if the strings overlap. No cap, those are the danger zones 😭.

🌸 Parameters 🌸

  • dest β€” pointer to the character array to write to.
  • src β€” pointer to the null-terminated byte string to copy from.

πŸ’– Return value πŸ’–

dest. That’s it. She gives you back the destination pointer, periodt ✨.

πŸŽ€ Example πŸŽ€

// Run this code

#include <cstring>
#include <iostream>
#include <memory>

int main()
{
    const char* src = "Take the test.";
//  src[0] = 'M'; // can't modify string literal
    auto dst = std::make_unique<char[]>(std::strlen(src) + 1); // +1
       for null terminator
    std::strcpy(dst.get(), src);
    dst[0] = 'M';
    std::cout << src << '\n' << dst.get() << '\n';
}

Lowkey obsessed with this little demo 🫢: it makes a std::unique_ptr<char[]> sized for the string plus the null terminator, copies with std::strcpy, then changes the first character of the copy. The commented line is literally // src[0] = 'M'; // can't modify string literal β€” string literals said β€œnot today” 😭.

🌈 Output 🌈

Take the test.
Make the test.

It prints both, and the second one starts with M while the original still starts with T β€” main character energy for sure πŸ‘‘.

πŸ‘‘ See also πŸ‘‘

  • strncpy β€” copies a certain amount of characters from one string to another (function)
  • memcpy β€” copies one buffer to another (function)
  • C documentation for strcpy

that’s the page, bestie 🫢 β€” source/version: http://cppreference.com, date: 2024.06.10, page: std::strcpy(3). go copy responsibly πŸ’…βœ¨

πŸ“¦ where this page comes from