Write a pointer version of the function
strcatthat we showed in Chapter 2: strcat(s, t) copies the stringtto the end ofs.
This is the version of strcat from Chapter 2:
void strcat(char s[], char t[]) {
int i, j;
i = j = 0;
while(s[i] != '\0') /* find the end of s */
i++;
while((s[i++] = t[j++]) != '\0') /* copy t */
;
}
Here is my solution:
void custom_strcat(char *s, char *t) {
while(*s) /* finding the end of the string */
s++;
while((*s++ = *t++)) /* copy t */
;
}
There are 2 while loops in my function, first loop will run until *s is equal to '\0'. At each iteration the value of s is incremented - thus, it will point to the next element;
The second loop will copy the elements of the string t at the and of s. The incrementation is done in the test part - even though after the loop stops s and t will point to other objects.This technique couldn't be applied in the first loop because when the loop stops s will point to an irrelevant value.
The exercise can be found at page 121 in K&R second edition.