-1

First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}

The above code yields outcome as below:

0x7ffea4a06150
LetsTry
size 32
`a���
`

I understand as ptr should output the address 0x7ffea4a06150

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 1
    You can use [`std::string::c_str`](https://www.cplusplus.com/reference/string/string/c_str/) that *"Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object."* – Jason Feb 08 '22 at 04:43

3 Answers3

1

Historically, in C language strings were just a memory areas filled with characters. Consequently, when a string was passed to a function, it was passed as a pointer to its very first character, of type char *, for mutable strings, or char const *, if the function had no intent to modify string's contents. Such strings were delimited with a zero-character ((char)0 a.k.a. '\0') at the end, so for a string of length 3 you had to allocate at least four bytes of memory (three characters of the string itself plus the zero terminator); and if you only had a pointer to a string's start, to know the size of the string you'd have to iterate it to find how far is the zero-char (the standard function strlen did it). Some standard functions accepted en extra parameter for a string size if you knew it in advance (those starting with strn or, more primitive and effective, those starting with mem), others did not. To concatenate two strings you first had to allocate a sufficient buffer to contain the result etc.

The standard functions that process char pointers can still be found in STL, under the <cstring> header: https://en.cppreference.com/w/cpp/header/cstring, and std::string has synonymous methods c_str() and data() that return char pointers to its contents, should you need it.

When you write a program in C++, its main function has the header of int main(int argc, char *argv[]), where argv is the array of char pointers that contains any command-line arguments your program was run with.

Ineffective as it is, this scheme could still be regarded as an advantage over strings of limited capacity or plain fixed-size character arrays, for instance in mid-nineties, when Borland introduced the PChar type in Turbo Pascal and added a unit that exported Pascal implementations of functions from C's string.h.

bipll
  • 11,747
  • 1
  • 18
  • 32
0

std::string and const char* are different types, reinterpret_cast<char*>(&data) means reinterpret the bits located at &data as const char*, which is not we want in this case.

so assuming we have type A and type B:

A a;
B b;

the following are conversion:

a = (A)b;                 //c sytle
// and                    
a = A(b);                 
// and 
a = static_cast<A>(b);    //c++ style

the following are bit reinterpretation:

a = *(A*)&b;                   //c style
// and
a = *reinterpret_cast<A*>(&b); //c++ style

finally, this should works:

int main() {
    string data = "LetsTry";
    const char *ptr = data.c_str();
    cout<< ptr << "\n";
}

bit reinterpretation is sometimes used, like when doing bit manipulation of a floating point number, but there are some rules to follow like this one What is the strict aliasing rule?

also note that cout << ptr << "\n"; is a specially case because feeds a pointer to std::cout usually output the address that pointer points to, but std::cout treats char* specially so that it output the content of that char array instead

dsukrect
  • 65
  • 6
-1

In C++, string is class and what you doing is creating a string object. So, to use are char * you need to convert it using c_str()

You can refer below code:

std::string data = "LetsTry";

// declaring character array
char * cstr = new char [data.length()+1];

// copying the contents of the
// string to char array
std::strcpy (cstr, data.c_str());

Now, you can get use char * to point your data.

Amol Saindane
  • 1,568
  • 10
  • 19
  • there's no reason to allocate memory just to point to a string. Just `ptr = data.c_str()` or `ptr = &data[0]` is enough. And even in case a new copy of the string is required, `memcpy` would be much better when the string length is known like this case – phuclv Feb 08 '22 at 05:20
  • `memcpy` holds no advantage over `strcpy` here. – Dúthomhas Feb 08 '22 at 05:25
  • Thanks Amol , i tried this and i can copy the string constant in char sequence . but my intention was to point the same address using data and cstr. – RudraBindu Feb 08 '22 at 05:31
  • @RudraBindu: I guess what you are looking not possible being its C++ string object – Amol Saindane Feb 08 '22 at 05:55