Possible Duplicate:
What is the difference between char s[] and char *s in C?
Do these statements about pointers have the same effect?
All this time I thought that whenever I need to copy a string(either literal or in a variable) I need to use strcpy(). However I recently found out this:
char a[]="test";
and this
char *a="test";
From what I understand the second type is unsafe and will print garbage in some cases. Is that correct? What made me even more curious is why the following doesn’t work:
char a[5];
a="test";
or this
char a[];
a="test";
but this works however
char *a;
a="test";
I would be greatful if someone could clear up things a bit.
Let’s examine case by case:
This tells the compiler to allocate 5 bytes on the stack, put
't''e''s''t'and'\0'on it. Then the variableapoints to where't'was written and you have a pointer pointing to a valid location with 5 available spaces. (That is if you viewaas a pointer. In truth, the compiler still treatsaas a single custom type that consists of 5chars. In an extreme case, you can imagine it something likestruct { char a, b, c, d, e; } a;)“test” (which like I said is basically
't''e''s''t'and'\0') is stored somewhere in your program, say a “literal’s area”, andais pointing to it. That area is not yours to modify but only to read.aby itself doesn’t have any specific memory (I am not talking about the 4/8 bytes of pointer value).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 5pushes 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 forato be an array of a size that would be determined when initialized. When there is no initialization, it’s just doesn’t make sense.You are defining
aas a pointer to arrays ofchar. When you assign it to"test",ajust points to it, it doesn’t have any specific memory for it though, exactly like the case ofchar *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.