strdup and strndup in C/C++



strdup()

The function strdup() is used to duplicate a string. It returns a pointer to a null-terminated byte string.

Syntax

Here is the syntax of strdup() in C language,

char *strdup(const char *string);

Example

Here is an example of strdup() in C language.

#include <stdio.h> #include<string.h> int main() { char *str = "Helloworld"; char *result; result = strdup(str); printf("The string : %s", result); return 0; }

Output

The string : Helloworld

strndup()

The function strndup works similarly to the function strndup(). This function duplicates the string at most size bytes i.e. the given size in the function. It also returns a pointer to a null-terminated byte string.

Syntax

Here is the syntax of strndup() in C language,

char *strndup(const char *string , size_t size);

Example

Here is an example of strndup() in C language,

#include <stdio.h> #include<string.h> int main() { char *str = "Helloworld"; char *result; result = strndup(str, 3); printf("The string : %s", result); return 0; }

Output

The string : Hel
Updated on: 2024-12-03T09:44:41+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements