Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize string pointer?

Tags:

c++

string

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
like image 456
Dinesh Dabhi Avatar asked Aug 08 '12 07:08

Dinesh Dabhi


People also ask

How do you initialize a string pointer in C++?

The pointer string is initialized to point to the character a in the string "abcd" . char *string = "abcd"; The following example defines weekdays as an array of pointers to string constants. Each element points to a different string.

How do I initialize the pointer?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .

How do you declare a string and initialize it?

To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).


2 Answers

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.

like image 153
AndersK Avatar answered Oct 12 '22 11:10

AndersK


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.

like image 44
juanchopanza Avatar answered Oct 12 '22 10:10

juanchopanza