How to use the address assignment of each other method In C++
This is the simplest and most efficient one. We can directly assign the address of 1st character of the string to a pointer to the char. This should be the preferred method unless your logic needs a copy of the string.
Example:
C++
// C++ program to convert string // to char array Using the address // assignment of each other method #include <iostream> #include <string> // Driver Code int main() { std::string s = "w3wiki" ; char * char_arr = &s[0]; std::cout << char_arr; return 0; } |
Output
w3wiki
- Time complexity: O(n)
- Auxiliary Space: O(1)
Convert String to Char Array in C++
Here, we will build a C++ program to convert strings to char arrays. Many of us have encountered the error ‘cannot convert std::string to char[] or char* data type’ so let’s solve this using 5 different methods:
- Using c_str() with strcpy()
- Using c_str() without strcpy()
- Using for loop
- Using the address assignment of each other method
- Using data() (C++17 and newer)
Input:
string s = "w3wiki";
Output:
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', '\0' };