I\'m currently learning C and I\'m confused with differences between char array and string, as well as how they work.
Question 1:
Why is the
Running source code one is undefined behavior because strlen()
requires a NUL-terminated string, which c[2] = "Hi"; /* = { 'H', 'i' } */
is not. A string differs from a char array in that a string is a char array with at least one NUL byte somewhere in the array.
The remaining answers should follow easily from this fact.
To autosize a char array to match the size of a string literal at initialization, simply specify no array size:
char c[] = "This will automatically size the c array (including the NUL).";
Note that you cannot compare char arrays with the == operator. You have to use
if (strcmp(c1, c2) == 0) {
/* Equal. */
} else {
/* Not equal. */
}