p
and q
are both variables. p
is of type "array of 12 char
" and q
is of type "pointer to char
". Both p
and q
have automatic storage duration. That is, they are allocated on the stack.
q
is a pointer and it is initialized to point to the initial character of the string "hello world"
. This string is a string literal, and all string literals have static storage duration.
p
is an array, so when you initialize p
with a string literal, it causes p
to declare an array of characters, and when it is initialized, the contents of the string literal are copied into the array. So, when GetMemory()
is called, space is allocated on the stack for the array p
, and the contents of the string literal "hello world"
are copied into that array.
No dynamic allocation is performed by your code.
Note that because q
is a pointer to an array of characters that have static storage duration, it is safe to return q
from the function: the array to which it points will exist for the entire duration of the program. It would not be safe to return p
, however, because p
ceases to exist when the function returns.
Note also that the type of "hello world"
is char const[12]
. There is an unsafe implicit conversion in C++ that allows a string literal to be converted to a char*
pointing to the initial character of the string literal. This is unsafe because it silently drops the const-qualification. You should always use const char*
when handling string literals, because the characters are not modifiable. (In the latest revision of the C++ language, C++11, this unsafe conversion has been removed.)