What is the difference between the following notations in string definition from a program address space point of view?
char str[20] = "Just to Ask";
char *str = "Just to Ask";
What is the difference between the following notations in string definition from a program address space point of view?
char str[20] = "Just to Ask";
char *str = "Just to Ask";
char str[20] = "Just to Ask";
The above statement defines an array str
of 20
characters and initializes the array with the string literal "Just to Ask"
. The above statement is equivalent to
char str[20] = {'J', 'u', 's', 't', ' ', 't', 'o', ' ', 'A', 's', 'k', '\0'};
The array initializer list has only 12
elements. The rest 8
elements of the array str
are initialized to 0
. If the array has automatic storage allocation, then it is allocated on the stack. If it has static storage allocation, then it is allocated in the data section of the program memory space.
The below statement
char *str = "Just to Ask";
defines str
not an array but a pointer which points to the string literal "Just to Ask"
. The string literal is read-only and attempting to modify it is undefined behaviour. Therefore, the two statements stated in your questions are totally different and the second statement better be written as
const char *str = "Just to Ask"; // string literal is read-only