The strncmp() and strdup() function in C

The strncmp() and strdup() are two string function used in C programming to compare two string and duplicate a string respectively. The strncmp() function can compare first n characters of a string with another string while strdup() can copy a string to another string. In this article we will see the use of strncmp() and strdup() functions in C programming.

strncmp() function in C language

strncmp() function is used to compare first n characters of two string. It compares only the first n characters. Syntax of strncmp() string functions is given bellow.

// syntax of strncmp() string function

int strncmp(const char *firstString, const char *secondString, size n);

Example of C program using strncmp() function.

// strncmp() function in C
#include <stdio.h>
#include <string.h>
int main(){
  char firstString[30] = "Competitive";
  char secondString[30] = "Competitive programmer";

  if (strncmp(firstString, secondString, 11) == 0){   // checking first 11 characters
    printf("string 1 and string 2 are equal");

    printf("string 1 and 2 are different");

return 0;

Output of strncmp() function program

strncmp() function in C

strdup() function in C programming

The strdup() string function is used to duplicate a string. See the example bellow.

// strdup() function in C
int main(){
    char mainString[] = "Competitive programmer\n";

    char* copiedString = strdup(mainString);

    printf("Main string is : %s\n", mainString);
    printf("Copied string is : %s\n", copiedString);

    return 0;

The program will give the following output if you compile and run it.

strdup() function in C