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:

  1. Using c_str() with strcpy()
  2. Using c_str() without strcpy()
  3. Using for loop
  4. Using the address assignment of each other method
  5. 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' };

Similar Reads

1. Using c_str() with strcpy()

A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring. The c_str() function is used to return a pointer to an array that contains a null-terminated sequence of characters representing the current value of the string....

2. Using c_str() without strcpy()

...

3. Using for loop

An alternate way of Method 1 can be such, without using strcpy() function. This option will not create a new string....

4. Using the address assignment of each other method

...

5. Using .data() (with C++17 or newer)

We can use for loop to iterate through each element of the std::string and assign the character to the char array one by one....

Contact Us