Pointers to char
char* pStr = new String("Hello");
char* s = "Hello";
Is the first one correct? Are there any开发者_C百科 difference between these two? My guess is that the first one is allocated on the heap,and the other one an the stack.Am i correct or are there any other differences?
The first one is just incorrect and won't compile because there is no such thing as String
in either C or C++. The second one will compile, and is fine in C(afaik). In C++, however, the conversion from a string literal to char*
is deprecated. You can unintentionally write later s[0] = 'X';
which is undefined behavior.
The correct way of doing it is using const (in C++)
const char * s = "Hello";
or, better, use string
std::string s("Hello");
pStr and s are pointers, so it is important to distinguish between the pointers themselves and the data that they point to.
On the first line, pStr is a pointer to an instance of the String class allocated on the heap. The string data inside this instance is a copy of a literal string "Hello" that is stored in the program's data segment. The copying is done by the String constructor. (You've referred to a String class, but I assume you mean std::string).
On the second line, s is a pointer to data stored in the program's data segment. Data in the data segment is immutable, so s should really be const char *.
There isn't enough information in your example to tell whether pStr and s are stored on the heap or the stack. If they are variables inside a function then they are on the stack. If there are members of a class then they are on the heap if the class was instantiated on the help (using new) or on the stack if it is instantiated as a value.
The line
char* pStr = new std::string("Hello");
will cause a compiler semantic error, because the LHS has a type of char*
and the RHS has a type of std::string
.
The line
char* s = "Hello"
will compile, but may give a warning, because the LHS has a type of char*
and the RHS has a type of const char*
.
精彩评论