Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. C Language Dictionary
  3. strcat() / strncat()

strcat() / strncat()

Functions that append one string to the end of another. You must ensure the destination buffer has enough space before calling these functions.

Syntax

// Appends src to the end of dst (overwrites dst's null terminator and adds src).
// Returns: a pointer to dst.
char *strcat(char *dst, const char *src);

// Appends at most n bytes of src to the end of dst. Always null-terminates the result.
// Returns: a pointer to dst.
char *strncat(char *dst, const char *src, size_t n);

Function Comparison

FunctionBuffer ProtectionNull-terminatedDescription
strcat()NoYesOverflows if dst does not have enough space. Use with caution.
strncat()Yes (up to n chars)YesPass the maximum number of characters to append as n — not the size of the dst buffer.

Sample Code

#include <stdio.h>
#include <string.h>

int main(void) {
    // Concatenate strings using strcat.
    char greeting[32] = "Hello";
    strcat(greeting, ", ");
    strcat(greeting, "World!");
    printf("%s\n", greeting); // Prints "Hello, World!".

    // Limit the number of appended characters using strncat.
    // Pass the maximum number of characters to append as n (not the buffer size).
    char buf[16] = "abc";
    strncat(buf, "XYZXYZXYZ", sizeof(buf) - strlen(buf) - 1);
    printf("%s\n", buf); // Prints "abcXYZXYZXY" (up to the remaining buffer space).

    // Safe concatenation using snprintf.
    char result[32] = "";
    const char *parts[] = {"foo", "bar", "baz"};
    for (int i = 0; i < 3; i++) {
        // Get the current length and calculate remaining capacity.
        size_t len = strlen(result);
        snprintf(result + len, sizeof(result) - len, "%s", parts[i]);
    }
    printf("snprintf concat: %s\n", result); // Prints "snprintf concat: foobarbaz".

    return 0;
}

Notes

strcat() does not check the available space in dst. If the concatenated string exceeds the buffer, a buffer overflow occurs. When working with dynamic data, use snprintf() to calculate the remaining capacity while concatenating.

The third argument of strncat() is the "maximum number of bytes to append," not the size of the dst buffer. The correct value to pass is sizeof(dst) - strlen(dst) - 1, where -1 reserves space for the null terminator.

For the basics of string copying, see strlen() / strcpy(). For string comparison, see strcmp().

If you find any errors or copyright issues, please .