-1

I dont know how to call it, I think its multidimensional char string. My problem is: I have this:

string serialnumber = "123456";

And I want to make this using code

char tmp6[] = { '1','2','3','4','5','6', 0 };
  • 1
    But why? You probably just need `serialnumber.c_str()`. => https://en.cppreference.com/w/cpp/string/basic_string/c_str – churill Apr 23 '20 at 14:30
  • 3
    Does this answer your question? [How to convert string to char array in C++?](https://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c) – surendra tomar Apr 23 '20 at 15:26

1 Answers1

-2

// assigning value to string s string s = "geeksforgeeks";

int n = s.length(); 

// declaring character array 
char char_array[n + 1]; 

// copying the contents of the 
// string to char array 
strcpy(char_array, s.c_str()); 

https://www.geeksforgeeks.org/convert-string-char-array-cpp/

  • Not legal C++ even if it is on the geeks for geeks web site. In C++ array bounds must be compile time constants, but in your code `n` is a variable. – john Apr 23 '20 at 14:32
  • 1
    Geeksforgeeks teaches such horrible practices. Not every compiler will eat `char char_array[n + 1];` it's non-standard. Also there is no need to copy anything at all. `s.c_str()` returns the required C-style-string. – churill Apr 23 '20 at 14:32
  • What about this link - https://stackoverflow.com/questions/13294067/how-to-convert-string-to-char-array-in-c – surendra tomar Apr 23 '20 at 14:43
  • Simplest way I can think of doing it is: string temp = "cat"; char tab2[1024]; strcpy(tab2, temp.c_str()); For safety, you might prefer: string temp = "cat"; char tab2[1024]; strncpy(tab2, temp.c_str(), sizeof(tab2)); tab2[sizeof(tab2) - 1] = 0; or could be in this fashion: string temp = "cat"; char * tab2 = new char [temp.length()+1]; strcpy (tab2, temp.c_str()); – surendra tomar Apr 23 '20 at 14:43
  • I raised this question as duplicate – surendra tomar Apr 23 '20 at 15:28