how character pointer could be used to point a string in c++?

1.5k Views Asked by At

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

3

There are 3 best solutions below

4
Amol Saindane On

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.

0
bipll On

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.

0
dsukrect On

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