5

I want to store the static value in string pointer is it posible?

If I do like

string *array = {"value"};

the error occurs

error: cannot convert 'const char*' to 'std::string*' in initialization
Frank Bollack
  • 24,478
  • 5
  • 49
  • 58
Dinesh Dabhi
  • 856
  • 1
  • 7
  • 18

4 Answers4

7

you would then need to write

string *array = new string("value");

although you are better off using

string array = "value";

as that is the intended way to use it. otherwise you need to keep track of memory.

AndersK
  • 35,813
  • 6
  • 60
  • 86
2

A std::string pointer has to point to an std::string object. What it actually points to depends on your use case. For example:

std::string s("value"); // initialize a string
std::string* p = &s; // p points to s

In the above example, p points to a local string with automatic storage duration. When it it gets destroyed, anything that points to it will point to garbage.

You can also make the pointer point to a dynamically allocated string, in which case you are in charge of releasing the resources when you are done:

std::string* p = new std::string("value"); // p points to dynamically allocated string
// ....
delete p; // release resources when done

You would be advised to use smart pointers instead of raw pointers to dynamically allocated objects.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

As array is an array of strings you could try this:

int main()
{
  string *array = new string[1]; 
  array[1] = "value";
  return 0;
}
Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
0

You can explicitly convert the literal to a string:

 std::string array[] = {std::string("value")};

Note that you have to define this as an array, not a pointer though. Of course, an array mostly makes sense if you have more than one element, like:

string array[] = {string("value1"), string("value2"), string("etc")};
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111