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!