Let's examine case by case:
char a[]="test";
This tells the compiler to allocate 5 bytes on the stack, put 't'
'e'
's'
't'
and '\0'
on it. Then the variable a
points to where 't'
was written and you have a pointer pointing to a valid location with 5 available spaces. (That is if you view a
as a pointer. In truth, the compiler still treats a
as a single custom type that consists of 5 char
s. In an extreme case, you can imagine it something like struct { char a, b, c, d, e; } a;
)
char *a="test";
"test" (which like I said is basically 't'
'e'
's'
't'
and '\0'
) is stored somewhere in your program, say a "literal's area", and a
is pointing to it. That area is not yours to modify but only to read. a
by itself doesn't have any specific memory (I am not talking about the 4/8 bytes of pointer value).
char a[5];
a = "test";
You are telling the compiler to copy the contents of one string over to another one. This is not a simple operation. In the case of char a[] = "test";
it was rather simple because it was just 5 push
es on the stack. In this case however it is a loop that needs to copy 1 by 1.
Defining char a[];
, well I don't think that's even possible, is it? You are asking for a
to be an array of a size that would be determined when initialized. When there is no initialization, it's just doesn't make sense.
char *a;
a = "test";
You are defining a
as a pointer to arrays of char
. When you assign it to "test"
, a
just points to it, it doesn't have any specific memory for it though, exactly like the case of char *a = "test";
Like I said, assigning arrays (whether null-terminated arrays of char (string) or any other array) is a non-trivial task that the compiler doesn't do for you, that is why you have functions for it.