C++ String strncat() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Bounded append

What You’ll Learn

The strncat() function appends up to num characters from a source C-string onto the end of a destination C-string, then adds a null terminator. It is the bounded version of strcat()—you choose how much of the source to copy when you do not want the entire string appended.

01

Append n Chars

Limit from source.

02

Null Terminate

Always adds \0.

03

Return dest

Pointer returned.

04

Buffer Size

Still your job.

05

vs strcat()

Full vs partial.

06

<cstring>

C library function.

Definition and Usage

In C++, strncat() is declared in <cstring>. It finds the existing null terminator of destination, then copies characters from source starting there—at most num characters, or until source ends if it is shorter than num.

After copying, strncat always writes a final '\0'. The destination must already contain a valid C-string (often initialized with text or "") and must have enough unused bytes for the append plus terminator.

💡
Beginner Tip

num limits source characters only. It does not mean “total buffer size.” Ensure sizeof(dest) > strlen(dest) + num (with room for \0) before calling strncat.

📝 Syntax

Function signature and a typical call:

C++
#include <cstring>

char* strncat(char* destination, const char* source, size_t num);

// Example:
char dest[20] = "Hello, ";
strncat(dest, "World!", 6);
// dest == "Hello, World!"

Parameters

  • destination — writable char array already holding a null-terminated string.
  • source — C-string to append from (not modified).
  • num — maximum number of characters to copy from source.

Return Value

Returns destination. The combined string is stored in the destination buffer.

⚡ Quick Reference

FunctionCopies from sourceNull-terminates?
strcat()Entire stringYes
strncat()At most num charsYes
strncpy()At most num charsNot always
std::string +=Full or substringAutomatic
Append
strncat(d, s, n)

Bounded concat

Min space
strlen(d)+n+1

Worst case bytes

Partial
strncat(d, s, 3)

First 3 chars only

Include
#include <cstring>

Header file

Examples Gallery

Compile with g++ strncat.cpp -std=c++17 -o strncat. Every example uses a destination buffer large enough for the final string plus '\0'.

📚 Getting Started

Append a bounded number of characters from source to destination.

Example 1 — Basic strncat() Usage

Append the first 6 characters of "World!" to "Hello, ".

C++
#include <iostream>
#include <cstring>

int main() {
    char destination[20] = "Hello, ";
    const char* source = "World!";

    std::strncat(destination, source, 6);

    std::cout << "Result: " << destination << "\n";
    std::cout << "Length: " << std::strlen(destination) << "\n";

    return 0;
}

How It Works

strncat starts at the null byte after "Hello, ", copies six characters World!, then writes '\0'. All six source characters fit within the limit num = 6.

Example 2 — Append Only Three Characters

Limit the append when you need a prefix of the source, not the full word.

C++
#include <iostream>
#include <cstring>

int main() {
    char label[32] = "File: ";
    const char* filename = "report_final.pdf";

    std::strncat(label, filename, 3); // only "rep"

    std::cout << label << "\n";
    return 0;
}

How It Works

With num = 3, only rep is copied from report_final.pdf. The rest of the filename is ignored—useful for truncated labels in fixed-width UI.

📈 Practical Patterns

Compare with strcat, handle short sources, and build paths step by step.

Example 3 — strncat() vs strcat()

See how limiting num changes the result on the same inputs.

C++
#include <iostream>
#include <cstring>

int main() {
    char bounded[24] = "C++: ";
    char full[24]    = "C++: ";
    const char* topic = "strncat tutorial";

    std::strncat(bounded, topic, 7);  // "strncat"
    std::strcat(full, topic);         // entire source

    std::cout << "strncat(7): " << bounded << "\n";
    std::cout << "strcat():   " << full << "\n";

    return 0;
}

How It Works

strncat with num = 7 copies exactly seven characters from source (no early null in that range). strcat continues until the source terminator.

Example 4 — When Source Is Shorter Than num

If source ends before num characters, strncat copies only what exists.

C++
#include <iostream>
#include <cstring>

int main() {
    char dest[16] = "Score: ";
    const char* points = "42";

    std::strncat(dest, points, 10); // source has only 2 chars + '\0'

    std::cout << dest << "\n";
    std::cout << "Length: " << std::strlen(dest) << "\n";

    return 0;
}

How It Works

Large num does not read past the source null terminator. Only "42" is appended; extra capacity in num is unused.

Example 5 — Build a Path in Steps

Chain small bounded appends when constructing a file path from parts.

C++
#include <iostream>
#include <cstring>

int main() {
    char path[64] = "";
    const char* root = "/home/user";
    const char* folder = "/projects";
    const char* file = "/main.cpp";

    std::strncat(path, root,   std::strlen(root));
    std::strncat(path, folder, std::strlen(folder));
    std::strncat(path, file,    std::strlen(file));

    std::cout << "Path: " << path << "\n";
    return 0;
}

How It Works

Using strlen(part) as num appends each segment fully while keeping an explicit bound. In new C++ code, std::filesystem::path is safer; this pattern shows how C-style APIs compose strings.

🚀 Common Use Cases

  • Truncated concatenation — append only a prefix of untrusted or long input.
  • Fixed-width fields — combine labels with limited suffix text.
  • Legacy C APIs — build messages in char buffers passed to older libraries.
  • Incremental path assembly — join path segments with explicit limits.
  • Teaching bounded I/O — step between unrestricted strcat and safer modern types.

🧠 How strncat() Works

1

Find end of dest

Scan destination until the existing '\0'.

Locate
2

Copy up to num

Copy characters from source, stopping at num or source '\0'.

Copy
3

Write terminator

Place '\0' after the last copied character.

Terminate

Return destination

Destination now holds the original text plus the bounded append.

📝 Notes

  • destination must already be null-terminated before the call.
  • num caps source length only—you must still size the destination buffer correctly.
  • strncat always null-terminates (unlike strncpy in edge cases).
  • Source and destination must not overlap (same rule as strcat).
  • Prefer std::string or std::string::append in new C++ application code.

⚡ Optimization

strncat() scans the destination to find its end on every call, so repeated appends to the same buffer cost O(n) per call. For many concatenations, track the write position or use std::string, which avoids rescanning from the start each time.

Conclusion

strncat() gives controlled appends from a source C-string while always keeping the result null-terminated. Use it when you need at most num characters from source, but still verify destination capacity yourself.

Next, learn strncmp() to compare at most n characters of two C-strings—the bounded counterpart to strcmp().

💡 Best Practices

✅ Do

  • Initialize destination as "" or with existing text
  • Verify buffer space: strlen(dest) + num + 1 <= capacity
  • Use strlen(source) as num to append a full segment safely
  • Prefer std::string for dynamic concatenation
  • Include <cstring> and use std::strncat

❌ Don’t

  • Assume num alone prevents buffer overflow
  • Call on an uninitialized destination array
  • Overlap source and destination memory
  • Use strncat when you mean strncpy (replace vs append)
  • Append unbounded user input without validating total length

Key Takeaways

Knowledge Unlocked

Five things to remember about strncat()

Use these points when appending to C-string buffers.

5
Core concepts
🔢 02

Always \0

Terminated.

Safety
🛡 03

Buffer Size

Your duty.

Rule
🔄 04

vs strcat

Partial vs full.

Compare
📝 05

Return dest

Same pointer.

Return

❓ Frequently Asked Questions

strncat() appends at most num characters from source to the end of destination, then writes a null terminator. Unlike strcat(), it limits how many source characters are copied—useful when source might be longer than you want to append.
char* strncat(char* destination, const char* source, size_t num); Include <cstring>. destination must already be a null-terminated string with enough remaining space for the appended characters plus '\0'.
It returns destination—the same pointer passed as the first argument. The destination buffer holds the combined string after the call.
Yes. strncat() always adds a '\0' after the appended characters. This differs from strncpy(), which may leave destination unterminated when num is smaller than the source length.
Not automatically. num only caps how many characters are taken from source—it does not check whether destination has enough total space. You must ensure the buffer can hold strlen(dest) + (characters appended) + 1 bytes.
strcat() appends the entire source string. strncat() appends at most num characters from source (or until source ends if shorter). Both require a large enough destination buffer; strncat() gives finer control over how much of source is copied.
Did you know?

The “n” in strncat limits characters copied from source, not the total size of the destination array. Decades of bugs came from assuming strncat was fully “safe” without checking how big destination actually is.

Continue the String Functions Series

Append with limits using strncat(), then compare with strncmp().

Next: strncmp() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful