Home >Backend Development >C++ >How to Convert a C String to a Character Array?

How to Convert a C String to a Character Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 06:36:02643browse

How to Convert a C   String to a Character Array?

Converting Strings to Character Arrays in C

When working with strings in C , you may encounter scenarios where converting a string to a character array is necessary. However, unlike converting to character pointers (char*), you aim to directly convert to a fixed-size character array (char[]).

To achieve this conversion, consider the following methods:

Method 1: Using strcpy and c_str()

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

This method utilizes the strcpy function to copy the string into the character array. c_str() converts the string to a null-terminated character array.

Method 2: Using strncpy and c_str()

For increased safety, you can use strncpy to ensure no buffer overflows occur:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

strncpy copies a specified number of characters into the array and sets the last character to null.

Method 3: Using New and c_str()

string temp = "cat";
char *tab2 = new char [temp.length()+1];
strcpy(tab2, temp.c_str());

This method dynamically allocates memory for the character array and then uses strcpy for copying.

The above is the detailed content of How to Convert a C String to a Character Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn