I just start learning C and found some confusion about the string pointer and string(array of char). Can anyone help me to clear my head a bit?
// source code
ch
You cannot directly reassign a value to an array type (e.g. your array of ten char
s name4
). To the compiler, name4
is an "array" and you cannot use the assignment =
operator to write to an array with a string literal.
In order to actually move the content of the string "Apple" into the ten byte array you allocated for it (name4
), you must use strcpy()
or something of that sort.
What you are doing with name3
is pretty different. It is created as a char *
and initialized to garbage, or zero (you don't know for sure at this point). Then, you assign into it the location of the static string "Apple". This is a string that lives in read-only memory, and attempting to write to the memory that the name3
pointer points to can never succeed.
Based on this, you can surmise that the last statement attempts to assign the memory location of a static string to something somewhere else that represents a collection of 10 char
s. The language does not provide you with a pre-determined way to perform this task.
Herein lies its power.