char *first = "Metal Gear";
char sentence1[10];
strcpy(sentence1, first);
This doesn't work because first
has 11 characters: the ten in the string, plus the null terminator. So you would need char sentence1[11];
or more.
strncpy(sentence2, second, sizeof(sentence2));
//shouldn't I specify the sizeof(source) instead of sizeof(destination)?
No. The third argument to strncpy
is supposed to be the size of the destination. The strncpy
function will always write exactly that many bytes.
If you want to use strncpy
you must also put a null terminator on (and there must be enough space for that terminator), unless you are sure that strlen(second) < sizeof sentence2
.
Generally speaking, strncpy
is almost never a good idea. If you want to put a null-terminated string into a buffer that might be too small, use snprintf
.
This is how I teach myself to program.
Learning C by trial and error is not good. The problem is that if you write bad code, you may never know. It might appear to work , and then fail later on. For example it depends on what lies in memory after sentence1
as to whether your strcpy
would step on any other variable's toes or not.
Learning from a book is by far and away the best idea. K&R 2 is a decent starting place if you don't have any other.
If you don't have a book, do look up online documentation for standard functions anyway. You could have learnt all this about strcpy
and strncpy
by reading their man pages, or their definitions in a C standard draft, etc.