The question has been well answered. What follows is just additional info on using strcpy and an alternative solution; You might have sometihing like the following:
Code:
int main(int argc, char** argv)
{
struct strc1
{
char msg1[20];
char msg2[5];
}talk;
strcpy(talk.msg1, argv[2]);
strcpy(talk.msg1, argv[1]);
printf("\nmsg1: %s\nmsg2: %s\n", talk.msg1, talk.msg2);
return 0;
}
The above will copy argv[1] to talk.msg1 and argv[2] to talk.msg2. talk.msg2 is initialised first to show the point while keeping your original structure.
If the first argument is over 20 characters, the program may or may not crash but there will
certainly be a buffer overrun in talk.msg2 (this means that the excess characters will be copied into char msg2 and overwrite part or all of what was initialised there).
Let's see an example:
compile the above code (name the program myprog) and call it like this:
./myprog 1234567890ABCDEFGHIJKL Hi!
The output is:
msg1: 1234567890ABCDEFGHIJKL
msg2: KL
The msg2 field should have held the string "Hi!"; this shows that the msg2 field has actually been corrupted from assigning to msg1. Also, the msg1 string is actually 22 characters long when used in so-called string functions.
One solution is to use strncpy and memset. strncpy will copy up to a specified number of characters but will not necessarily append a null terminator.
Use memset to initialise your buffers with nulls and specifiy a string lenth one less than the target buffer to insure that your buffer is null terminated:
Code:
int main(int argc, char** argv)
{
struct strc1
{
char msg1[20];
char msg2[5];
}talk;
memset(talk.msg1, 0, sizeof(talk.msg1));
memset(talk.msg2, 0, sizeof(talk.msg2));
strncpy(talk.msg2, argv[2], sizeof(talk.msg2)-1);
strncpy(talk.msg1, argv[1], sizeof(talk.msg1)-1);
printf("\nmsg1: %s\nmsg2: %s\n", talk.msg1, talk.msg2);
return 0;
}
You could of course use memset on the entire struct (use the address of talk):