As long as the string fits in the target space, even
char str[] = "some text";
strcpy(str, "text");
is well-defined.
char field1[256];
declares an array with room for 256 characters. This allows you to store a null-terminated string of up to 255 characters (the array size, minus one for the null terminator).
char str[256] = "some text";
additionally initializes the array to contain the string "some text"
. You can still copy a string of up to 255 characters into the array, since that's how much room there is.
char str[] = "some text";
is exactly identical to char str[10] = "some text";
. With the empty brackets, str
is still an array of characters. What the empty brackets mean is that the size of the array (what would normally go inside the brackets) is determined automatically. There is no other difference compared with brackets with a size in it. For an array of characters, the size is the length of the string plus one for the null terminator.
In all cases involving an array, the string used to initialize the array (if there is one) is stored in the array itself. It isn't accessible in any other way, and if you change the array, the string that was used to initialize it is not present in memory anymore (at least in the sense that there's no way to find it — there's no guarantee that it won't be present in a memory dump, but you have no way to access it from your program).
The critical difference is not between char str[10]
and char str[]
, but between char str[…]
and char *p
. With a *
instead of brackets, char *p
declares a pointer, not an array.
char *p = "some text";
does two things. One thing is that it arranges for a string literal "some text"
to be stored somewhere that's accessible for the whole duration of the program. Another thing is that it declares a variable p
that points to this string literal. You cannot modify the memory where "some text"
is stored (in practice, on many platforms, it's in read-only memory). On the other hand, you can make something else point to that memory, and you can change p
to point to something else.
char *p = "some text";
char *q;
puts(p); // prints "some text"
q = p;
p = "hello";
puts(q); // prints "some text"
puts(p); '// prints "hello"