Hey there,
I'm currently trying to get into C.
While messing around with strcpy I had some unexpected results that I don't really understand.
So I wrote this method to switch the values of two string vars:
void switchValues(char* first, char* second)
{
int size = sizeof(second);
char temp[size];
strcpy(temp, second);
strcpy(second, first);
strcpy(first, temp);
}
As long as first and second point to arrays of the same size everything works fine.
If one is smaller, it should not work correctly - as we should expect.
My problem is with the way it does not work correctly.
I call it like this
char name1[] = "John";
char name2[] = "James";
switchValues(name1, name2);
As long as the size of name2 is greater everything still works.
Before
name1: John
name2: James
After
name1: James
name2: John
But if name1 contains the greater value I end up with some weird concatenation.
Before
name1: James
name2: John
After
name1: John
name2: JamesJohn
Does anybody know why there is a difference based on the size of the arrays - and more importantly - why it ends up in concatenation?
I mean name1 should not fit into name2, yet name2 ends up being both values together.