I just want someone who can clarify parts of this example program from my C++ book so I can understand it better. As I'm learning C++ from a book.
Basically this example program is a customized version of the function strcat() that just has the added feature to copy certain amount of characters from s2 onto the end of s1.
The area in which I don't 100% understand is inside the function mystrcat(), I understand what is in main().
The code:
1 2
// find end of s1
while(*s1) s1++;
just finds the end of s1 and leaves it there?
The code: if(len==0) len = strlen(s2); I understand.
I understand that this loop runs while *s2 & len are true. The code *s1 = *s2; just adds the chars from s2 onto the end as s1 is set from the end of its string array?
Furthermore, I get why you need s2++; but not why you have s1++; in the function mystrcat() as I thought it is already at the end of its string by the code:
1 2
// find end of s1
while(*s1) s1++;
.
Lastly, I understand the len--; in the function just to let you know.
Line 28 in mystrcat is incrementing s1 until the null byte at the end of the destination string is found.
Line 33 *s1 = *s2; is copying a single character from s2 to s1 (from source string to destination string).
After that, both s1 and s2 are incremented in order to point to the next character in the source and destination. If s1 was not incremented each time, then all the characters of s2 would simply overwrite the same single location in the destination string.
At line 39 a new null terminator is added. Again, if s1 had not been incremented, this would overwrite the last character copied. In fact it would overwrite the only character copied, leaving the destination string unchanged.
Line 28 in mystrcat is incrementing s1 until the null byte at the end of the destination string is found.
Line 33 *s1 = *s2; is copying a single character from s2 to s1 (from source string to destination string).
After that, both s1 and s2 are incremented in order to point to the next character in the source and destination. If s1 was not incremented each time, then all the characters of s2 would simply overwrite the same single location in the destination string.
At line 39 a new null terminator is added. Again, if s1 had not been incremented, this would overwrite the last character copied. In fact it would overwrite the only character copied, leaving the destination string unchanged.
Wow, thanks.
I can see how it all works now, as a beginner you just get so confused and I'm I this website to ask people!