std::strncpy(3)

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

okay so bestie, this is the std::strncpy(3) page from the C++ Standard Libary manual πŸ’…βœ¨ buckle up, because copying strings has lore.

🌸 NAME 🌸

std::strncpy β€” std::strncpy (yes, it’s giving β€œthe name is the name,” iconic πŸŽ€)

✨ Synopsis ✨

Defined in header <cstring>
char* strncpy( char* dest, const char* src, std::size_t count );

okay so what it does: copies at most count characters of the byte string pointed to by src β€” and yes, that includes the terminating null character β€” to the character array pointed to by dest πŸ’–

  • If count is reached before the entire string src was copied, the resulting character array is not null-terminated. Periodt, that’s the rule 😭
  • If, after copying the terminating null character from src, count is not reached, additional null characters are written to dest until the total of count characters have been written ✨
  • If the strings overlap, the behavior is undefined. Like, do not. No cap. πŸ’€

🫢 Parameters 🫢

  • dest β€” pointer to the character array to copy to πŸ’…
  • src β€” pointer to the byte string to copy from πŸ¦‹
  • count β€” maximum number of characters to copy πŸŽ€

πŸ’– Return value πŸ’–

dest β€” that’s it, that’s the return value, bestie πŸ‘‘

πŸŽ€ Example πŸŽ€

       // Run this code

        #include <cstring>
        #include <iostream>

        int main()
        {
            const char* src = "hi";
            char dest[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
            std::strncpy(dest, src, 5);

            std::cout << "The contents of dest are: ";
            for (char c : dest)
            {
                if (c)
                    std::cout << c << ' ';
                else
                    std::cout << "\\0" << ' ';
            }
            std::cout << '\n';
        }

πŸŒ€ Output πŸŒ€

The contents of dest are: h i \0 \0 \0 f

πŸ‘€ See also πŸ‘€

  • strcpy β€” copies one string to another (function) 🌈
  • memcpy β€” copies one buffer to another (function) ⭐
  • C documentation for strncpy β€” the C docs for strncpy, right there in the see-also list πŸ’œ

πŸ’– source/version: http://cppreference.com Β· date: 2024.06.10 Β· page: std::strncpy(3) β€” that’s the footer, bestie, and we ate πŸ’…βœ¨

πŸ“¦ where this page comes from