One way to initialize the array - which is related to your second example - is by doing:
char foo[] = {'a', 'b', 'c'};
In this syntax, to the right side of =
you provide the array elements as comma separeted values inside a { }
. So in the above example, array foo
has three elements. First is a
, second is b
, and third is c
. If you wanted a \0
at the end, you need to do it explicitly as char foo[] = {'a', 'b', 'c', '\0'};
.
Regarding your second example, answer by @molbdnilo already explains what is semantically wrong with your statment char *der={'a','a','a','a','a'};
. If you want to define der
as array and initialize it using { }
, you can do:
char der[] = {'a','a','a','a','a'};
This way you are actually defining a char array and initializing it with the content you want.
Note that, you NEED to mention the array size if you are not initializing it while defining it. Which means:
char foo[]; // Will give error because no size is mentioned
char foo[10]; // Fine because size is given as 10
However, mentioning size is optional if you initialize the array while defining it, as we saw in the examples above. But, if you mention the size and if your initializer is smaller than the array size, remaining elements will be initialized to 0
. Like:
char bar[10] = {'a', 'b', 'c', '\0'};
/* Your arrays' content will be 'a', 'b', 'c', '\0',
* and all remaning 6 elements will be 0
*/