-1

I need some help understanding how to convert string to a char *pointer.

string text;

char *str = &text[0];

Could someone please kindly explain to me how does the conversion of text to char in the above case work?

Saeed
  • 3,294
  • 5
  • 35
  • 52
Dwoidia
  • 113
  • 1
  • 8
  • 1
    Use the `.c_str()` member function. And make your `str` variable `const`. – Jesper Juhl Jan 27 '19 at 16:28
  • 1
    there is no conversion taking place, `text[0]` is a `char` and with `&` you get a pointer to it – 463035818_is_not_an_ai Jan 27 '19 at 16:30
  • `text[0]` is a `char` being the first character of the string. `&text[0]` is a pointer to that `char`. So it is a `char*`. It is probably worth reading a good book to get the fundamentals https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list: – Galik Jan 27 '19 at 16:33

1 Answers1

0

If text is a string then text[0] is not just a char but a char& to the specified char (a reference to the char), so &text[0] is a char*

But warning, the internal char* of a string may not be null terminated, this is why c_str() exists and forces the null terminating char to be present, and also returns a const pointer because of course this is more secure

bruno
  • 32,421
  • 7
  • 25
  • 37