bintom said:
What are the differences between the following methods of declaring
strings?
char string1[20] = "C++ forum";
char* string2 = "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.
It's not just notation: string1 is an array of chars, while string2 is a
pointer to char. A string-literal, such as "C++ forum", denotes an
object of static duration. For this reason there's no danger in writing
e.g.:
char const * f()
{
return "something" ;
}
but the following is a recipe for disaster:
char const * f()
{
char const arr[] = "something" ;
return arr ; // DON'T DO THIS!
}
In your first example you use the static duration object just as a
source to initialize string1 (in fact, it is likely that the compiler
will optimize away that source), whereas in the second one you directly
point to it (its first character, actually; and it may be the same
string literal object of the first line, or not; the implementation must
document this). Since attempting to modify the object corresponding to a
string literal yields undefined behavior you should add const:
char const * string2 = "C++ forum" ;
Omitting the const is allowed for backward-compatibility but deprecated.
Of course, you can modify string1, instead.