What is the difference between:
char arr[20]="I am a string"
and
char *arr="I am a string"
How is it possible to initialize an array just by using a pointer?
What is the difference between:
char arr[20]="I am a string"
and
char *arr="I am a string"
How is it possible to initialize an array just by using a pointer?
First one is clear, it is an array initialisation, whereas the second one means that character pointer *arr is pointing to the unnamed static array which will store the String " I am a string".
One difference is in allocated storage size. First expression allocates 20 chars, but the second expression allocate the length of the string (13 chars).
The second difference is mentioned in this post. which is discussed on the way how these variables are allocated.
In first case you are partially initializing stack allocated array with 14 chars taken from buffer represented by "I am a string"
string literal.
In second case you are initializing stack allocated pointer with a pointer to a buffer with static storage duration represented by "I am a string"
string literal. Also notice that in second case you should use const char *arr
.