As Original Griff noted in solution 1, you need to use
strcpy
to assign a value to an array variable. What may not be quite clear is that you
can initialize an array variable with a string.
In your case, you cannot have a space between the square brackets when defining an array e.g.
char first_name[] = "John";
char last_name[ ] = "Smith";
first_name = "Stephen";
strcpy(first_name, "Stephen");
In the above snippet of code, when we define
first_name
we get an array of 5 chars { 'J', 'o', 'h', 'n', '\0' }. Like any other C variable, it does not, and cannot change size, so if we call
strcpy(first_name, "Stephen")
we will assign the first 5 letters of "Stephen" to the storage reserved for
first_name
and the remaining letters will most likely overwrite other program variables - Though that is not necessarily the case - the situation invokes the dreaded "undefined behavior". It might be that your C compiler and library is smart enough to detect the overwrite and either truncate the assignment, or possibly even throw an exception, terminating the program. What happens in this case is defined in the standard as
undefined. Compiler writers are free to do what they want when dealing with undefined behavior, possibly causing a system crash, formatting the system drives, or starting a global thermonuclear war!