strncat() in C: Append Part of a String

strncat() appends at most n characters from the source string and then adds a terminating null character. The destination still needs enough capacity for its existing text, the appended characters and \0.

Syntax Top ↑

strncat(destination, source, n);

Append Five Characters Top ↑

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

int main(void) {
    char destination[30] = "welcome to ";
    char source[] = "plus2net";

    strncat(destination, source, 5);
    printf("%s\n", destination);
    return 0;
}

Output

welcome to plus2

Check Available Capacity Top ↑

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

int main(void) {
    char destination[20] = "Plus2Net ";
    char source[] = "C Tutorial";
    size_t count = 5;
    size_t available = sizeof(destination) - strlen(destination) - 1;

    if (count > available) {
        count = available;
    }

    strncat(destination, source, count);
    printf("%s\n", destination);
    return 0;
}

How strncat() Works Top ↑

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

char *custom_strncat(char *destination, const char *source, size_t n) {
    char *end = destination + strlen(destination);

    while (*source != '\0' && n > 0) {
        *end++ = *source++;
        n--;
    }

    *end = '\0';
    return destination;
}

int main(void) {
    char destination[20] = "Hello, ";

    custom_strncat(destination, "World!", 3);
    printf("%s\n", destination);
    return 0;
}

Output

Hello, Wor




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer