James Kanze
10/6/2008 12:38:00 PM
On Oct 5, 9:13 pm, bintom <binoythomas1...@gmail.com> wrote:
> What are the differences between the following methods of
> declaring strings?
> char string1[20] = "C++ forum";
This declares an array of char, initialized with
{
'C', '+', '+', ' ', 'f',
'o', 'r', 'u', 'm', '\0',
'\0', '\0', '\0', '\0', '\0',
'\0', '\0', '\0', '\0', '\0'
} ;
> char* string2 = "C++ forum";
This is really incorrect, and requires a deprecated conversion
in order for it to compile. It's the equivalent of declaring a
static char const hidden[ 10 ] =
{
'C', '+', '+', ' ', 'f',
'o', 'r', 'u', 'm', '\0'
} ;
and initializing string2 with its address.
Neither are used to declare "strings" in C++; one defines an
array of char, and the other a pointer to char. To declare a
string:
std::string string1( "C++ forum" ) ;
.
> I know that the first uses the array notation, whereas the
> second uses pointer notation. But apart from that what are the
> implications / dangers, etc. if any.
The implication is that they are two very different statements,
declaring different types of objects.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34