A short answer won't do your question justice. You're asking about two of the most significant, but often misunderstood, aspects of C.
First of all, in C, by definition, a string is an array of characters, terminated with a nul character, '\0'
.
So if you say
char string1[] = "Hello";
it's as if you had said
char string1[] = {'H', 'e', 'l', 'l', 'o', '\0'};
When you use a string constant like "Hello"
in your program, the compiler automatically constructs the array for you, as a convenience.
Next we have the character pointer type, char *
. You called this a "string to a char array", but it's really a pointer to a single char
. People often refer to char *
as being C's "string type", and in a way it is, but it can be a misleading thing to say, because not every char *
is a string, and more importantly C has very few mechanisms for automatically managing strings for you. (What I mean is that, in C, you can't just sling strings around as if they were a basic data type, like you can in C++ or BASIC. You typically have to worry about where they're stored, how they're allocated.)
But let's go back to the definition of a string. If a string is an array of characters, then why would a pointer to characters be useful for manipulating strings at all? And the answer is, pointers are always useful for manipulating arrays in C; pointers are so good at manipulating arrays that sometimes it seems as if they are arrays. (But don't worry, they're not.)
I can't delve into a full treatise on the relationship between arrays and pointers in C here, but a couple of points must be made:
If you say something like
char *string2 = "world";
what actually happens (what the compiler does for you automatically) is as if you had written
static char __temporaryarray[] = "world";
char *string2 = __temporaryarray;
And, actually, since string2
is a pointer to a character (that is, what it points at is characters, not whole arrays of characters), it's really:
char *string2 = &__temporaryarray[0];
(That is, the pointer actually points to the array's first element.)
So since a string is always an array, when you mentioned the string "world"
in a context where you weren't using it to initialize an array, C went ahead and created the array for you, and then made the pointer point to it. C does this whenever you have a string constant lying around in your program. So you can later say
string2 = "sailor";
and you can also say things like
if(strcmp(string1, "Goodbye") == 0) { ... }
Just don't do
char *string3;
strcpy(string3, "Rutabaga"); /* WRONG!! *//
That's very wrong, and won't work reliably at all, because nobody allocates any memory for string3
to point to, for strcpy
to copy the string into.
So to answer your question, you will sometimes see strings created or manipulated as if they are arrays, because that's what they actually are. But you will often see them manipulated using pointers (char *
), because this can be extremely convenient, as long as you know what you are doing.