Your program has undefined behavior.
Your array b
contains { '1', '2' }
. As you say, there is no null character in the array -- which means it doesn't contain a string.
strcpy
's second argument must be a pointer to a string. You gave it a char*
value that is not a pointer to a string.
In practice, strcpy
will probably continue copying characters from the memory following b
. That memory contains arbitrary garbage -- and even the attempt to access it has undefined behavior.
In a sense, you're lucky that you got output that is visibly garbage. If there had happened to be a null character immediately following your array in memory, and if your program didn't blow up trying to access it, it could have just printed 12
, and you might not have known that your program is buggy.
If you want to correct your program, you can change
char b[2] = "12";
to
char b[] = "12";
The compiler will figure out how big b
needs to be to hold the string (including the required terminating null character).