How to copy a string using strncpy() in C++

The strncpy() function is a built-in library function that is declared in the string.h header file. The function copies the source string to a destination string until a null character( \0 ) is reached.

Syntax

char * strcpy (char * Dest, char * Src);

In C++, style strings (i.e., string) cannot be passed as a parameter in the strncpy() fucntion. The string.c_str() is used to convert the string to char str[].

1 of 10

Implementation

// C++ program
#include <bits/stdc++.h>
using namespace std;
// driver code
int main()
{
string str = "Educative";
int size = str.length();
char char_arr[size + 1];
// copying
strcpy(char_arr, str.c_str());
for (int i = 0; i < size; i++)
cout << char_arr[i];
return 0;
}

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved