C strncat() Function Tutorial

In this section, we will learn what the strncat() function is and how to use it in C.

String Concatenation in C: strncat() Function

Sometimes we have two character-strings and we want to concatenate them. This is where we can use the `strncat` function to do the operatoin.

The prototype of this function exists in the `string.h` header file and so we need to include that header file if we want to use the function.

Note: there’s another function named `strcat` by which we can concatenate two strings together. The difference is that the strcat function doesn’t put a limit on the number of characters that should be copied from the second character-string to the first character-string. But using the strncat() function, we can specify the number of characters to be copied from the second string to the first one.

strncat() Function Syntax

Here’s the prototype of the `strncat` function:

char* strncat( char* dest, const char* src, size_t count );

strncat() Function Parameters

  • The first parameter of this function is the address of the first character-string that we want to attach a new character-string to the end of it.
  • The second parameter is the address of the character-string that we want to get a copy and attach it to the end of the first character-string.

Note: the second character-string won’t change in this operation.

  • The third parameter of this function is the number of characters that we want to copy from the second character-string (second parameter) and add it to the end of the first character-string (first parameter).

strncat() Function Return Value

The return value of this method is the address of the first character-string (first parameter).

Example: C String Concatenation via strncat() Function

#include <stdio.h>
#include <string.h>
int main() {

    char array[50] = "Hi, ";

    strncat(array, "this is for test",6);

    puts(array);
    return 0;
}

Output:

Hi, this i

As you can see in this example, we wanted to copy only 6 characters of the second argument (the second character-string) and so as a result, the characters `this i` are copied from the second argument and appended to the first argument.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies