And main:
Code:
int main(void)
{
char source[7]="qwerty", target[7];
cpystring (source, target);
return 0;
}
The reasons why your code don't work.
1. char source[6]="qwerty";
you have 6 characters + additional character calle zero character ('\0') that terminates string. Remember string is just ordinary array of characters that ends with special character '\0'. So you always must to make a room for it.
2.
You are incrementing source. That is pointer to first element in the array in the begining. After you increment it you are trying to display it with puts() but what is the address of pointer source and what is the value on which points to after while?
For example at the start of your function source has this value:
0x0012fed0, that is the address (beacuse source is a pointer) of first element (byte) in the array and that is letter 'q'. After while
value of pointer variable source is: 0x0012fed7, because there is 7 elements (including '\0') and source is pointing to a byte of memory immediately after '\0' and what is on that memory? You don't know. That's why you get rgarbage characters.
Another solution would be:
Code:
void cpystring(const char *source, char *target)
{
char *p=target;
char *m=(char*) source;
while (*p++=*m++);
puts (target);
puts (source);
}
Cheers!